Debian Codegraph @

doc/tools/rocqrst/notations/parsing.py

raw symbols SCIP
1 ##########################################################################
2 ## # The Rocq Prover / The Rocq Development Team ##
3 ## v # Copyright INRIA, CNRS and contributors ##
4 ## <O___,, # (see version control and CREDITS file for authors & dates) ##
5 ## \VV/ ###############################################################
6 ## // # This file is distributed under the terms of the ##
7 ## # GNU Lesser General Public License Version 2.1 ##
8 ## # (see LICENSE file for the text of the license) ##
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 # Only print ANTLR version warning once
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 # Using "Recognizer.checkVersion" would cause endless recursion
26 check_version(*args, **kwargs)
27 checked_version = True
28 Recognizer.checkVersion = checkVersion_once
29
30 SUBSTITUTIONS = [#("@bindings_list", "{+ (@id := @val) }"),
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()