Debian Codegraph @

doc/tools/rocqrst/notations/regexp.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 """An experimental visitor for ANTLR notation ASTs, producing regular expressions."""
11
12 import re
13 from io import StringIO
14
15 from .parsing import parse
16 from .TacticNotationsParser import TacticNotationsParser
17 from .TacticNotationsVisitor import TacticNotationsVisitor
18
19 class TacticNotationsToRegexpVisitor(TacticNotationsVisitor):
20 def __init__(self):
21 self.buffer = StringIO()
22
23 def visitRepeat(self, ctx:TacticNotationsParser.RepeatContext):
24 separator = ctx.ATOM()
25 repeat_marker = ctx.LGROUP().getText()[1]
26
27 self.buffer.write("(")
28 self.visitChildren(ctx)
29 self.buffer.write(")")
30
31 if repeat_marker in ["?", "*"]:
32 self.buffer.write("?")
33 elif repeat_marker in ["+", "*"]:
34 self.buffer.write("(")
35 self.buffer.write(r"\s*" + re.escape(separator.getText() if separator else " ") + r"\s*")
36 self.visitChildren(ctx)
37 self.buffer.write(")*")
38
39 def visitCurlies(self, ctx:TacticNotationsParser.CurliesContext):
40 self.buffer.write(r"\{")
41 self.visitChildren(ctx)
42 self.buffer.write(r"\}")
43
44 def visitAtomic(self, ctx:TacticNotationsParser.AtomicContext):
45 self.buffer.write(re.escape(ctx.ATOM().getText()))
46
47 def visitHole(self, ctx:TacticNotationsParser.HoleContext):
48 self.buffer.write("([^();. \n]+)") # FIXME could allow more things
49
50 def visitMeta(self, ctx:TacticNotationsParser.MetaContext):
51 self.buffer.write(re.escape(ctx.METACHAR().getText()[1:]))
52
53 def visitWhitespace(self, ctx:TacticNotationsParser.WhitespaceContext):
54 self.buffer.write(r"\s+")
55
56 def regexpify(notation):
57 """Translate notation to a Python regular expression matching it"""
58 vs = TacticNotationsToRegexpVisitor()
59 vs.visit(parse(notation))
60 return vs.buffer.getvalue()