Skip to content

Commit

Permalink
Add the typemap feature
Browse files Browse the repository at this point in the history
  • Loading branch information
BenBaryoPX committed Nov 12, 2024
1 parent 4dd5900 commit 30aa363
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ npm install
- Tracks scope and connects each declaration to its references.
See [eslint-scope](https://github.com/eslint/eslint-scope) for more info on the scopes used.
- Adds a unique id to each node to simplify tracking and understanding relations between nodes.
- Maps the types to the node ids for easier access.
- <u>Arborist</u> - marks nodes for replacement or deletion and applies all changes in a single iteration over the tree.

### flAST Data Structure
Expand Down
6 changes: 5 additions & 1 deletion src/flast.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function parseCode(inputCode, opts = {}) {

const excludedParentKeys = [
'type', 'start', 'end', 'range', 'sourceType', 'comments', 'srcClosure', 'nodeId',
'childNodes', 'parentNode', 'parentKey', 'scope',
'childNodes', 'parentNode', 'parentKey', 'scope', 'typeMap', 'lineage', 'allScopes',
];

/**
Expand Down Expand Up @@ -123,6 +123,7 @@ function extractNodesFromRoot(rootNode, opts) {
opts = { ...generateFlatASTDefaultOptions, ...opts };
const tree = [];
let nodeId = 0;
const typeMap = {};

// noinspection JSUnusedGlobalSymbols
estraverse.traverse(rootNode, {
Expand All @@ -133,6 +134,8 @@ function extractNodesFromRoot(rootNode, opts) {
enter(node, parentNode) {
tree.push(node);
node.nodeId = nodeId++;
if (!typeMap[node.type]) typeMap[node.type] = [node.nodeId];
else typeMap[node.type].push(node.nodeId);
node.childNodes = [];
node.parentNode = parentNode;
node.parentKey = parentNode ? getParentKey(node) : '';
Expand All @@ -146,6 +149,7 @@ function extractNodesFromRoot(rootNode, opts) {
});
}
});
if (tree?.length) tree[0].typeMap = typeMap;
return tree;
}

Expand Down
18 changes: 18 additions & 0 deletions tests/parsing.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,22 @@ describe('Parsing tests', () => {
const result = generateCode(ast[0]);
assert.strictEqual(result, expected);
});
it(`Verify the type map is generated accurately`, () => {
const code = `class a {
static b = 1;
#c = 2;
}`;
const expected = {
Program: [0],
ClassDeclaration: [1],
Identifier: [2, 5],
ClassBody: [3],
PropertyDefinition: [4, 7],
Literal: [6, 9],
PrivateIdentifier: [8],
};
const ast = generateFlatAST(code);
const result = ast[0].typeMap;
assert.deepEqual(result, expected);
});
});

0 comments on commit 30aa363

Please sign in to comment.