Skip to content

Commit

Permalink
Do not crash on invalid JavaScript
Browse files Browse the repository at this point in the history
  • Loading branch information
niknetniko committed May 29, 2024
1 parent fd673a5 commit 5b3c125
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions tested/languages/javascript/parseAst.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
const { parse } = require('abstract-syntax-tree');
const fs = require('fs');
const source = fs.readFileSync(process.argv[2], 'utf-8');
// Add next option to support more javascript features
const ast = parse(source, {next: true}).body;

function mapSubTreeToIds(subtree) {
const type = subtree.type;
Expand All @@ -11,7 +9,7 @@ function mapSubTreeToIds(subtree) {
} else if (type === 'FunctionDeclaration' || type === 'ClassDeclaration') {
return [subtree.id];
} else if (type === 'ExpressionStatement' &&
subtree.expression.type === 'AssignmentExpression') {
subtree.expression.type === 'AssignmentExpression') {
return [subtree.expression.left];
} else {
return [];
Expand All @@ -31,6 +29,15 @@ function mapIdToName(id) {
}
}

// Use Set to remove duplicates
const array = Array.from(new Set(ast.flatMap(mapSubTreeToIds).flatMap(mapIdToName)));
console.log(array.join(', '));
let ast;
try {
// Add next option to support more JavaScript features.
const ast = parse(source, {next: true}).body;
// Use Set to remove duplicates
const array = Array.from(new Set(ast.flatMap(mapSubTreeToIds).flatMap(mapIdToName)));
console.log(array.join(', '));
} catch (e) {
// Assume this is invalid JavaScript at this point.
console.error(e);
process.exit(0);
}

0 comments on commit 5b3c125

Please sign in to comment.