Skip to content

Instantly share code, notes, and snippets.

@willcrichton
Last active January 21, 2024 14:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save willcrichton/de595e0820d275468691f2fcc25e0ce7 to your computer and use it in GitHub Desktop.
Save willcrichton/de595e0820d275468691f2fcc25e0ce7 to your computer and use it in GitHub Desktop.
class SitterTree {
tree: Parser.Tree
node_types: {[key: string]: NodeType}
constructor(tree: Parser.Tree) {
this.tree = tree;
this.node_types = {};
}
private node_group(): NodeGroup {
const group = new NodeGroup(Object.values(this.node_types).sort((a, b) => a.id - b.id));
return group.extend(styleTags({
'" string': "string",
"identifier": "variableName",
"assignment": "definition"
}));
}
private build_node(node: Parser.SyntaxNode): number[] {
const buffer = _.flatten(node.children.map((child) => this.build_node(child)));
if (!this.node_types.hasOwnProperty(node.type)) {
this.node_types[node.type] = new NodeType(node.type, {}, Object.keys(this.node_types).length);
}
const node_type = this.node_types[node.type];
return buffer.concat([node_type.id, node.startIndex, node.endIndex, buffer.length + 4]);
}
build(): Tree {
const buffer = this.build_node(this.tree.rootNode);
const group = this.node_group();
return Tree.build({buffer, group});
}
}
@dit7ya
Copy link

dit7ya commented Apr 1, 2023

I arrived here from https://discuss.codemirror.net/t/mapping-tree-sitter-trees-to-lezer-trees/2362/5

Is this a general solution for translating any tree-sitter grammar to lezer grammar?

If yes, could you please add a few lines of instructions on how to get started?

Thanks a lot in advance.

@willcrichton
Copy link
Author

Sorry, I don't remember anything about this code. Good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment