sarsamurmu / estree-toolkit

Tools for working with ESTree AST
https://estree-toolkit.netlify.app/
MIT License
54 stars 1 forks source link

Is there a way to declare a visitor method that will called if no more specific methods exist? #16

Closed retorquere closed 4 months ago

retorquere commented 6 months ago

Something like

const argumentsVisitor = {
  Identifier(path) {
    console.log(path.node.name)
  },

  Node(path) {
    console.log(path.node.type)
  },
}

that will print all types except Identifier?

sarsamurmu commented 6 months ago

It's currently not possible. What case do you have that needs this functionality?

retorquere commented 6 months ago

It's bound to be an incredibly niche case -- I use a severely restricted subset of javascript as a configuration format for a tool I'm building, and I used the catch-all to detect disallowed syntax. I got what I need with

const definitions = require('estree-toolkit/dist/definitions')
function catchall(visitor) {
  if (visitor.Node) {
    let types = []
    for (const type in definitions.definitions) {
      if (type === 'Node') continue
      if (!visitor[type]) types.push(type)
    }
    if (types.length) visitor[types.sort().join('|')] = visitor.Node
    delete visitor.Node
  }
  return visitor
}
retorquere commented 6 months ago

This library is a delight to work with BTW. I'm rewriting from recast and in two days I've gotten so much cleaner code than I used to.

sarsamurmu commented 4 months ago

Thank you for your kind words!