Disable duplicate declaration validation in Acorn

Tags: , , ,



I’m using Acorn to parse some syntactically valid JavaScript code into an ESTree for further processing. It appears that Acorn does some semantic checks too – in particular it throws an error for duplicate declarations. For example, parsing the following code throws an error of Identifier 'f' has already been declared:

function f() { return 1; }
function f() { return 2; }

I do not want such semantic errors to be checked – I’m doing custom processing on the resultant ESTree, so the semantic validity of the source code does not matter to me.

I’ve looked though the Acorn options for the parse(input, options) function, but I could not find anything that sounds like what I want.

Is there a way to disable such semantic checking?

Answer

It seems like there is no proper way to disable semantic validation. I managed to get what I want with an ugly hack, by overriding the raiseRecoverable method.

This worked for me (note that I’m using TypeScript here, but it would of course be possible to do the same in plain JavaScript):

import { Parser } from "acorn";
class SyntacticParser extends Parser {
  raiseRecoverable(pos: any, message: string) {
    if (message.includes("Identifier ") && message.includes(" has already been declared")) return;
    (Parser.prototype as any).raiseRecoverable.call(this, pos, message); // weird call syntax required because the TypeScript types for Parser doesn't contain the `raiseRecoverable` method
  }
}

It’s an ugly hack because I’m filtering out the duplicate declaration message based on the stringified error message. However, there does not appear to be a better way.



Source: stackoverflow