Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Utility for knowing if an Identifier is a reference to a binding #10

Open
Rich-Harris opened this issue Aug 11, 2023 · 3 comments
Open

Comments

@Rich-Harris
Copy link
Contributor

When traversing an AST, is there an easy way to know if an Identifier node references a binding or not? In other words, this code...

const ast = parse(`foo; obj.bar`);

traverse(ast, {
  $: { scope: true },
  Identifier(path) {
    console.log(path.node.name);
  }
});

...will log this...

foo
obj
bar

...but only foo and obj are binding references. I have a package for this — is-reference — but it would be awesome if there was a way to do this within estree-toolkit. Thank you!

@sarsamurmu
Copy link
Owner

sarsamurmu commented Aug 11, 2023

It's possible, currently there's no built-in utility function but you can make yourself one

const ast = parseModule(`
const foo = 0, obj = {};
const bar = 0;

foo;
obj.bar;
`);

/**
 * @param {NodePath} path 
 */
const isReference = (path) => {
  const binding = path.scope.getBinding(path.node.name);
  if (binding != null) {
    return path === binding.identifierPath || binding.references.includes(path)
  }
  return false
}

traverse(ast, {
  $: { scope: true },
  Identifier(path) {
    console.log(path.node.name, isReference(path))
  }
})

Output

foo true
obj true
bar true
foo true
obj true
bar false

@Rich-Harris
Copy link
Contributor Author

Wonderful, thanks! That works for us — I'll leave this issue open in case you intend to expose a utility like that, but otherwise please consider this resolved

@sarsamurmu
Copy link
Owner

Just leaving this issue open, I will add this functionality to the library later

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants