| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
from .TacticNotationsLexer import TacticNotationsLexer |
| 11 |
from .TacticNotationsParser import TacticNotationsParser |
| 12 |
|
| 13 |
from antlr4 import CommonTokenStream, InputStream |
| 14 |
from antlr4.error.ErrorListener import ErrorListener |
| 15 |
from antlr4.Recognizer import Recognizer |
| 16 |
|
| 17 |
import os |
| 18 |
|
| 19 |
|
| 20 |
checked_version = False |
| 21 |
check_version = Recognizer.checkVersion |
| 22 |
def checkVersion_once(*args, **kwargs): |
| 23 |
global checked_version |
| 24 |
if not checked_version and os.getenv ("ROCQ_DEBUG_REFMAN"): |
| 25 |
|
| 26 |
check_version(*args, **kwargs) |
| 27 |
checked_version = True |
| 28 |
Recognizer.checkVersion = checkVersion_once |
| 29 |
|
| 30 |
SUBSTITUTIONS = [ |
| 31 |
("@qualid_or_string", "@id|@string")] |
| 32 |
|
| 33 |
class ParseError(Exception): |
| 34 |
def __init__(self, msg): |
| 35 |
super().__init__() |
| 36 |
self.msg = msg |
| 37 |
|
| 38 |
class ExceptionRaisingErrorListener(ErrorListener): |
| 39 |
def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e): |
| 40 |
raise ParseError("{}:{}: {}".format(line, column, msg)) |
| 41 |
|
| 42 |
ERROR_LISTENER = ExceptionRaisingErrorListener() |
| 43 |
|
| 44 |
def substitute(notation): |
| 45 |
"""Perform common substitutions in the notation string. |
| 46 |
|
| 47 |
Nested notations quickly became unwieldy in the original ‘…’-based format, |
| 48 |
so they were avoided and replaced by pointers to grammar rules. With the |
| 49 |
new format, it's usually nicer to remove the indirection. |
| 50 |
""" |
| 51 |
for (src, dst) in SUBSTITUTIONS: |
| 52 |
notation = notation.replace(src, dst) |
| 53 |
return notation |
| 54 |
|
| 55 |
def parse(notation): |
| 56 |
"""Parse a notation string, optionally reporting errors to `error_listener`. |
| 57 |
|
| 58 |
:return: An ANTLR AST. Use one of the supplied visitors (or write your own) |
| 59 |
to turn it into useful output. |
| 60 |
""" |
| 61 |
substituted = substitute(notation) |
| 62 |
lexer = TacticNotationsLexer(InputStream(substituted)) |
| 63 |
parser = TacticNotationsParser(CommonTokenStream(lexer)) |
| 64 |
parser.addErrorListener(ERROR_LISTENER) |
| 65 |
return parser.top() |