benjamn / ast-types

Esprima-compatible implementation of the Mozilla JS Parser API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Failing to traverse identifier in type annotation

robz opened this issue · comments

commented

The following:

const flowParser = require('flow-parser');
const recast = require("recast");
const types = require("ast-types");

const parser = {
  parse: code => flowParser.parse(code, {types: true}),
};

const ast = recast.parse(
  `
    class A<B> extends C<D> {}
    function f<E>() {}
  `,
  {parser}
);

const typeParam = ast.program.body[0].typeParameters.params[0];
console.log(typeParam.name, typeParam.type);

const superTypeParam = ast.program.body[0].superTypeParameters.params[0].id;
console.log(superTypeParam.name, superTypeParam.type);

const functionTypeParam = ast.program.body[1].typeParameters.params[0];
console.log(functionTypeParam.name, functionTypeParam.type);

types.visit(ast, {
  visitIdentifier: function(path) {
    console.log('visiting ', path.node.name);
    return false;
  }
});

Outputs this:

B TypeParameter
D Identifier
E TypeParameter
visiting A
visiting C
visiting f

ast-types is failing to visit "B", "D", and "E". I can see why "B" and "E" might be skipped (even though TypeParameters should be considered Identifiers as well--that may be a bug in the flow parser). However, I'm fairly certain that "D" should be visited.

I am encountering the same issue but in TS instead of in Flow
I noticed this in jscodeshift and I created an issue on their repo: facebook/jscodeshift#389
But I think the .traverse function comes from this lib instead