google / google/jsir

Refactor our AST traversal C++ API to make it more like @babel/traverse

Open
#27 0 comments 0 reactions 0 assignees View on GitHub
enhancement
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.