Search code examples
javascriptregexantlr4

JavaScript recursive/circular regexps


I have an ANTLR4 grammar file and there is a pair of circularly-dependent rules, if you can call them that. Here are those rules:

call
    : ID LPAREN (expr (COMMA expr)*)? RPAREN 
    ;

expr
    : operand
    | call
    | NOT expr
    | expr (AND|OR|ADD|SUB|MUL|DIV) expr
    | expr LSQUARE expr RSQUARE
    ;

call references expr, and expr references call. What I'm looking for is a way to implement such string checks using JavaScript RegExp. It would also help to have some sort of recursive RegExp for the expr rule, but something tells me that whatever could solve the circular dependency issue would solve the recursion issue as well. If it exists, that is :)

I tried:

  • Using (?R)? in the regexp, but JavaScript's RegExps don't seem to have this functionality
  • Using XRegExp.matchRecursive, but, judging by the API description and by what I got then playing around with it, it is not exactly what I'm looking for
  • Creating my own custom RecursiveRegExp class with an overridden constructor and exec() method, but it appears that I'm not skilled in JS enough to pull off something like this :)

Is there a way to, perhaps, insert a "link" to another RegExp into a RegExp literal, or something like that?


Solution

  • What I'm looking for is a way to implement such string checks using JavaScript RegExp.

    That is not possible.

    What you can do is use the ANTLR grammar that defines ANTLR itself and generate JavaScript parser. That parser can then be used to parse the grammar containing the call and expr rules. The resulting parse tree can then be used to discover which rule references what other rule(s).