|
| 1 | +import {syntaxError} from "./syntaxError.js"; |
| 2 | + |
| 3 | +export function findDeclarations(node, globals, input) { |
| 4 | + if (node.type !== "Program") throw new Error(`unexpected type: ${node.type}`); |
| 5 | + |
| 6 | + const declarations = []; |
| 7 | + |
| 8 | + function declareLocal(node) { |
| 9 | + if (globals.has(node.name) || node.name === "arguments") { |
| 10 | + throw syntaxError(`Global '${node.name}' cannot be redefined`, node, input); |
| 11 | + } |
| 12 | + declarations.push(node); |
| 13 | + } |
| 14 | + |
| 15 | + function declarePattern(node) { |
| 16 | + switch (node.type) { |
| 17 | + case "Identifier": |
| 18 | + declareLocal(node); |
| 19 | + break; |
| 20 | + case "ObjectPattern": |
| 21 | + node.properties.forEach((node) => declarePattern(node)); |
| 22 | + break; |
| 23 | + case "ArrayPattern": |
| 24 | + node.elements.forEach((node) => node && declarePattern(node)); |
| 25 | + break; |
| 26 | + case "Property": |
| 27 | + declarePattern(node.value); |
| 28 | + break; |
| 29 | + case "RestElement": |
| 30 | + declarePattern(node.argument); |
| 31 | + break; |
| 32 | + case "AssignmentPattern": |
| 33 | + declarePattern(node.left); |
| 34 | + break; |
| 35 | + default: |
| 36 | + throw new Error("Unrecognized pattern type: " + node.type); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + for (const child of node.body) { |
| 41 | + switch (child.type) { |
| 42 | + case "VariableDeclaration": |
| 43 | + child.declarations.forEach((declaration) => declarePattern(declaration.id)); |
| 44 | + break; |
| 45 | + case "ClassDeclaration": |
| 46 | + case "FunctionDeclaration": |
| 47 | + declareLocal(child.id); |
| 48 | + break; |
| 49 | + case "ImportDefaultSpecifier": |
| 50 | + case "ImportSpecifier": |
| 51 | + case "ImportNamespaceSpecifier": |
| 52 | + declareLocal(child.local); |
| 53 | + break; |
| 54 | + case "Class": |
| 55 | + case "Function": |
| 56 | + throw new Error(`unexpected type: ${child.type}`); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return declarations; |
| 61 | +} |
0 commit comments