Ejemplo n.º 1
0
    def except_(self, arg: SyntaxArgument) -> ArgumentPattern:
        """ EXCEPT - approve value if it doesnt contain any symbol from inclusion """
        if not arg.inclusion:
            raise PatternError(
                "Except argument expression have to contain not less than one symbol in inclusion"
            )
        elif not len(arg.name.strip(EXCEPT)):
            raise PatternError("Except expression should be named")

        pattern = "[^" + arg.inclusion.translate(ESCAPE) + "]"

        return "(?P<{}>{}+)".format(arg.name.strip(EXCEPT), pattern)
Ejemplo n.º 2
0
 def regex(self, arg: SyntaxArgument) -> ArgumentPattern:
     """ REGEX - inclusion is regex """
     if not arg.inclusion:
         raise PatternError(
             "Regex argument expression have to contain not less than one symbol in inclusion"
         )
     return arg.inclusion
Ejemplo n.º 3
0
    def union(self, arg: SyntaxArgument) -> ArgumentPattern:
        """ UNION - splits value afterwards with given inclusion """
        if not len(arg.name.strip(UNION)):
            raise PatternError("Union argument should be named")

        pattern = "(?P<" + arg.name.strip(UNION) + ">.*)"
        return pattern
Ejemplo n.º 4
0
    def one_char(self, arg: SyntaxArgument) -> ArgumentPattern:
        """ ONE_CHAR - every symbol of inclusion is possible char to be taken """
        if not len(arg.name.strip(ONE_CHAR)):
            raise PatternError("Char argument should be named")

        pattern = "."
        if arg.inclusion:
            # inclusions = ["\\" + inc for inc in list(inclusion[arg])]
            pattern = "[" + arg.inclusion.translate(ESCAPE) + "]"

        return "(?P<" + arg.name.strip(ONE_CHAR) + ">" + pattern + ")"
Ejemplo n.º 5
0
    def recursion_arg(arg: SyntaxArgument) -> RecursionArgument:
        """ Makes inner pattern data to handle ahead the parsing """
        pattern = arg.inclusion

        # [legacy] 0.5.93
        if pattern is not None and pattern.startswith(
                '"') and pattern.endswith('"'):
            pattern = pattern[1:-1]

        if not pattern:
            raise PatternError("Recursion argument expression have to contain "
                               "not less than one symbol in inclusion")

        return RecursionArgument(pattern, {"text": pattern})
Ejemplo n.º 6
0
    def __init__(
        self,
        text: str,
        regex: str = "{}$",
        lazy: bool = True,
        flags: typing.Optional[re.RegexFlag] = None,
        default_validators: typing.Optional[typing.List[str]] = None,
        nestings: typing.Optional[typing.Dict[str, typing.Callable[
            [str], typing.Any]]] = None,
        **context,
    ):
        super().__init__(text, regex, lazy)

        self.syntax = Syntax()
        self.text = text
        self.regex = regex
        self.lazy = lazy

        context["flags"] = flags
        context["default_validators"] = default_validators
        context["nestings"] = nestings

        # Find all validated arguments
        validated_arguments: typing.List[typing.Tuple[str, str]]

        if context["default_validators"] is not None:
            validated_arguments = [
                (arg[0][0:-1] + ":" + ":".join(context["default_validators"]) +
                 ">", arg[1]) for arg in syntax.ARGS_FINDALL.findall(text)
            ]
        else:
            validated_arguments = syntax.TYPED_ARGS_FINDALL.findall(text)

        # Parse arguments and save validators
        self.validators = get_validators(validated_arguments, nestings)
        self.validation = {p.name: p.validation for p in self.validators}

        # Delete arguments from text
        text = syntax.ARGS_DELETE.sub(syntax.ARGUMENT, text)

        # Save inclusion from text
        inclusions: typing.List[
            typing.Optional[str]] = context.get("inclusions") or [
                get_inclusion(argument)
                for argument in re.findall(syntax.ARGS_NAME_FINDALL, text)
            ]

        # Delete inclusion from text
        text = syntax.INCLUSION_DELETE.sub(syntax.ARGUMENT, text)

        # Add representation
        self.representation: str = re.sub(syntax.ARGS_NAME_FINDALL,
                                          context.get("repr_noun", "?"), text)

        self.arguments: typing.List[str] = re.findall(syntax.ARGS_NAME_FINDALL,
                                                      text)
        self.inclusions = dict(zip(self.arguments, inclusions))
        self.recursions: typing.Dict[str, RecursionArgument] = {}

        # Add escape symbols
        text = text.translate(syntax.ESCAPE)

        # Reveal arguments
        for i, argument in enumerate(self.arguments):
            syntax_argument = SyntaxArgument(argument, i,
                                             self.inclusions.get(argument))

            if not argument:
                raise PatternError("Argument cannot be empty")
            elif argument.startswith(syntax.RECURSION):
                self.recursions[argument] = self.syntax.recursion_arg(
                    syntax_argument)
                print(self.recursions)

            if argument[0] in syntax.SYNTAX_CHARS:
                text = text.replace(
                    "<{}>".format(argument.translate(syntax.ESCAPE)),
                    self.syntax.get_syntax(argument[0])(self.syntax,
                                                        syntax_argument),
                )
            else:
                pre = self.inclusions.get(argument) or ""
                text = text.replace(
                    f"<{argument}>",
                    f"(?P<{argument}>{pre}.*{'?' if lazy else ''})")

        self.compiler = re.compile(regex.format(text),
                                   flags=context.get("flags") or 0)
        self.pregmatch: typing.Optional[dict] = None
        self.ahead = AheadValidation(Pattern, self.inclusions, self.validators,
                                     self.recursions)
Ejemplo n.º 7
0
 def ignore(self, arg: SyntaxArgument) -> ArgumentPattern:
     if arg.inclusion or arg.name.strip(IGNORE):
         raise PatternError(
             "Inclusion and name in ignore-argument are forbidden")
     return "(?:.*?)"
Ejemplo n.º 8
0
 def anything(self, arg: SyntaxArgument) -> ArgumentPattern:
     if arg.inclusion or arg.name.strip(ANYTHING):
         raise PatternError(
             "Inclusion and name in anything-argument are forbidden")
     return "(?:.+)"