estree-toolkit icon indicating copy to clipboard operation
estree-toolkit copied to clipboard

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

Open retorquere opened this issue 9 months ago • 3 comments

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?

retorquere avatar May 10 '24 13:05 retorquere

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

sarsamurmu avatar May 11 '24 16:05 sarsamurmu

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 avatar May 11 '24 23:05 retorquere

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.

retorquere avatar May 12 '24 00:05 retorquere

Thank you for your kind words!

sarsamurmu avatar Jul 11 '24 10:07 sarsamurmu