Refactor our AST traversal C++ API to make it more like @babel/traverse
- Dominant language
- C++
- Stars
- 664
- Forks
- 30
- Avg merge
- 4d 9h
- Merged PRs (30d)
- 11
Description
If we rewrite the examples from https://babel.dev/docs/babel-traverse into TypeScript:
```typescript
import * as parser from "@babel/parser";
import {traverse, NodePath} from "@babel/traverse";
import * as t from "@babel/types";
const code = `function square(n) {
return n * n;
}`;
const ast = parser.parse(code);
traverse(ast, {
enter(path: NodePath) {
if (path.isIdentifier({ name: "n" })) {
// path: NodePath
// path.node: Identifier
path.node.name = "x";
}
},
});
```
```typescript
traverse(ast, {
FunctionDeclaration: function(path: NodePath) {
path.node.id.name = "x";
},
});
```
There is a critical class `NodePath`, which has the following functionalities:
* It stores the entire **path** from the root node to the current node;
* It provides a method `parent()` that returns the parent `NodePath`;
* It provides mutation methods:
* `path.replaceWith(newNode)`
* `path.remove()`
* `path.insertBefore(nodes)` and `path.insertAfter(nodes)`
* `path.replaceWithMultiple(nodes)`
* It's covariant: a `NodePath` is a `NodePath`.
Contributor guide
Assessment
This issue has not been assessed yet.