Skip to content

Commit

Permalink
patterns: export to Python regex, which will be helpful for implement…
Browse files Browse the repository at this point in the history
…ing #1 and maybe #2
  • Loading branch information
Vít Šesták 'v6ak committed May 28, 2024
1 parent e822d8c commit a9d5071
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions pyi3l/patterns.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from dataclasses import dataclass
from abc import ABC, abstractmethod
from typing import List
from typing import List, Optional
from .util import pcre_quote
from functools import reduce


class Pattern(ABC):
@abstractmethod
def to_pcre(self): pass

@abstractmethod
def to_python_re(self): pass

@abstractmethod
def map_chars(self, f): pass
Expand Down Expand Up @@ -72,7 +75,10 @@ class Literal(Pattern):

def to_pcre(self):
return pcre_quote(self.s)


def to_python_re(self):
return re.escape(self.s)

def map_chars(self, f):
return Literal("".join(map(f, self.s)))

Expand All @@ -85,6 +91,9 @@ def __add__(self, other: "Pattern"):
class Anything(Pattern):
def to_pcre(self):
return ".*"

def to_python_re(self):
return ".*"

def map_chars(self, f):
return self
Expand All @@ -96,6 +105,9 @@ class AnyOf(Pattern):
def to_pcre(self):
return "(" + "|".join(map(lambda p: p.to_pcre(), self.variants)) + ")"

def to_python_re(self):
return "(" + "|".join(map(lambda p: p.to_python_re(), self.variants)) + ")"

def map_chars(self, f):
return AnyOf(
variants=list(map(lambda p: p.map_chars(f), self.variants)),
Expand All @@ -115,6 +127,9 @@ def __add__(self, other: "Pattern"):

def to_pcre(self):
return "".join(map(lambda p: p.to_pcre(), self.subpatterns))

def to_python_re(self):
return "".join(map(lambda p: p.to_python_re(), self.subpatterns))

def map_chars(self, f):
return CompoundPattern(
Expand All @@ -132,9 +147,16 @@ class Raw(Pattern):
# Please use composable PCRE regexes (without modifiers, without ^ and $)
# ^ and $ will be added automatically afterwards
pattern: str

python_re: Optional[str]

def to_pcre(self):
return self.pattern


def to_python_re(self):
if self.python_re is not None:
return self.python_re
else:
raise NotImplementedError(f'No Python regex alternative for {self.pattern}')

def map_chars(self, f):
raise Error(f"Cannot map chars of raw pattern {self}")

0 comments on commit a9d5071

Please sign in to comment.