| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 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]+)") |
| 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() |