Skip to content

Parsers

ValidationMessage dataclass

A message from a parser that indicates the result of a validation.

Source code in src/typedlogic/parser.py
10
11
12
13
14
15
16
17
18
19
20
21
22
@dataclass
class ValidationMessage:
    """
    A message from a parser that indicates the result of a validation.
    """

    message: str
    line: Optional[int] = None
    column: Optional[int] = None
    level: str = field(default="error")

    def __str__(self):
        return f"{self.level}: {self.message} at line {self.line}, column {self.column}"

Parser dataclass

Bases: ABC

A parser is a class that can parse a source and return a Theory object.

You can use the registry get_parser method to get a parser for a particular syntax:

>>> from typedlogic.registry import get_parser
>>> parser = get_parser("yaml")
Source code in src/typedlogic/parser.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
@dataclass
class Parser(ABC):
    """
    A parser is a class that can parse a source and return a Theory object.

    You can use the registry `get_parser` method to get a parser for a particular syntax:

        >>> from typedlogic.registry import get_parser
        >>> parser = get_parser("yaml")


    """

    default_suffix: ClassVar[str] = "txt"
    auto_validate: Optional[bool] = None

    def parse_file(self, source: Union[Path, str, TextIO], **kwargs) -> Theory:
        if isinstance(source, str):
            source = Path(source)
        return self.parse(source, **kwargs)

    @abstractmethod
    def parse(self, source: Union[Path, str, TextIO], **kwargs) -> Theory:
        """
        Parse a source and return a Theory object.

        TODO: in future, if the source is a text representation, use parse_text() instead.

        :param source: A path to a file, a string representation of the source, or a file-like object.
        :param kwargs:
        :return:
        """
        pass

    def parse_text(self, source: str, **kwargs) -> Theory:
        """
        Parse a text string and return a Theory object.

        :param source:
        :param kwargs:
        :return:
        """
        return self.parse(source, **kwargs)

    def parse_to_sentences(self, source: Union[Path, str, TextIO], **kwargs) -> List[Sentence]:
        """
        Parse a source and return a list of sentences.

        .. note::

            This method is a convenience method that calls `parse` and returns the sentences from the resulting Theory.

        :param source:
        :param kwargs:
        :return:
        """
        theory = self.parse(source, **kwargs)
        return theory.sentences

    def parse_ground_terms(self, source: Union[Path, str, TextIO], **kwargs) -> List[Term]:
        """
        Parse a source and return a list of ground terms (facts).

        :param source:
        :param kwargs:
        :return:
        """
        theory = self.parse(source, **kwargs)
        return theory.ground_terms

    def translate(self, source: Any, **kwargs) -> Theory:
        """
        Translate a source object into a Theory object.

        The type of the source object may be constrained by individual subclasses

        :param source:
        :param kwargs:
        :return:
        """
        if isinstance(source, ModuleType):
            if not source.__file__:
                raise ValueError("Module must have a file attribute")
            return self.parse(source.__file__, **kwargs)
        raise NotImplementedError("Translation not supported by this parser")

    def validate_iter(self, source: Union[Path, str, TextIO], **kwargs) -> Iterator[ValidationMessage]:
        """
        Validate a source and return an iterator of validation messages.

        Validation might include type checking (for python source), syntax checking (for text source),
        linting, etc.

        :param source:
        :param kwargs:
        :return:
        """
        return iter([])

    def validate(self, source: Union[Path, str, TextIO], **kwargs) -> List[ValidationMessage]:
        """
        Validate a source and return a list of validation messages.

        :param source:
        :param kwargs:
        :return:
        """
        return list(self.validate_iter(source, **kwargs))

parse(source, **kwargs) abstractmethod

Parse a source and return a Theory object.

TODO: in future, if the source is a text representation, use parse_text() instead.

Parameters:

Name Type Description Default
source Union[Path, str, TextIO]

A path to a file, a string representation of the source, or a file-like object.

required
kwargs
{}

Returns:

Type Description
Theory
Source code in src/typedlogic/parser.py
46
47
48
49
50
51
52
53
54
55
56
57
@abstractmethod
def parse(self, source: Union[Path, str, TextIO], **kwargs) -> Theory:
    """
    Parse a source and return a Theory object.

    TODO: in future, if the source is a text representation, use parse_text() instead.

    :param source: A path to a file, a string representation of the source, or a file-like object.
    :param kwargs:
    :return:
    """
    pass

parse_text(source, **kwargs)

Parse a text string and return a Theory object.

Parameters:

Name Type Description Default
source str
required
kwargs
{}

Returns:

Type Description
Theory
Source code in src/typedlogic/parser.py
59
60
61
62
63
64
65
66
67
def parse_text(self, source: str, **kwargs) -> Theory:
    """
    Parse a text string and return a Theory object.

    :param source:
    :param kwargs:
    :return:
    """
    return self.parse(source, **kwargs)

parse_to_sentences(source, **kwargs)

Parse a source and return a list of sentences.

.. note::

This method is a convenience method that calls `parse` and returns the sentences from the resulting Theory.

Parameters:

Name Type Description Default
source Union[Path, str, TextIO]
required
kwargs
{}

Returns:

Type Description
List[Sentence]
Source code in src/typedlogic/parser.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def parse_to_sentences(self, source: Union[Path, str, TextIO], **kwargs) -> List[Sentence]:
    """
    Parse a source and return a list of sentences.

    .. note::

        This method is a convenience method that calls `parse` and returns the sentences from the resulting Theory.

    :param source:
    :param kwargs:
    :return:
    """
    theory = self.parse(source, **kwargs)
    return theory.sentences

parse_ground_terms(source, **kwargs)

Parse a source and return a list of ground terms (facts).

Parameters:

Name Type Description Default
source Union[Path, str, TextIO]
required
kwargs
{}

Returns:

Type Description
List[Term]
Source code in src/typedlogic/parser.py
84
85
86
87
88
89
90
91
92
93
def parse_ground_terms(self, source: Union[Path, str, TextIO], **kwargs) -> List[Term]:
    """
    Parse a source and return a list of ground terms (facts).

    :param source:
    :param kwargs:
    :return:
    """
    theory = self.parse(source, **kwargs)
    return theory.ground_terms

translate(source, **kwargs)

Translate a source object into a Theory object.

The type of the source object may be constrained by individual subclasses

Parameters:

Name Type Description Default
source Any
required
kwargs
{}

Returns:

Type Description
Theory
Source code in src/typedlogic/parser.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def translate(self, source: Any, **kwargs) -> Theory:
    """
    Translate a source object into a Theory object.

    The type of the source object may be constrained by individual subclasses

    :param source:
    :param kwargs:
    :return:
    """
    if isinstance(source, ModuleType):
        if not source.__file__:
            raise ValueError("Module must have a file attribute")
        return self.parse(source.__file__, **kwargs)
    raise NotImplementedError("Translation not supported by this parser")

validate_iter(source, **kwargs)

Validate a source and return an iterator of validation messages.

Validation might include type checking (for python source), syntax checking (for text source), linting, etc.

Parameters:

Name Type Description Default
source Union[Path, str, TextIO]
required
kwargs
{}

Returns:

Type Description
Iterator[ValidationMessage]
Source code in src/typedlogic/parser.py
111
112
113
114
115
116
117
118
119
120
121
122
def validate_iter(self, source: Union[Path, str, TextIO], **kwargs) -> Iterator[ValidationMessage]:
    """
    Validate a source and return an iterator of validation messages.

    Validation might include type checking (for python source), syntax checking (for text source),
    linting, etc.

    :param source:
    :param kwargs:
    :return:
    """
    return iter([])

validate(source, **kwargs)

Validate a source and return a list of validation messages.

Parameters:

Name Type Description Default
source Union[Path, str, TextIO]
required
kwargs
{}

Returns:

Type Description
List[ValidationMessage]
Source code in src/typedlogic/parser.py
124
125
126
127
128
129
130
131
132
def validate(self, source: Union[Path, str, TextIO], **kwargs) -> List[ValidationMessage]:
    """
    Validate a source and return a list of validation messages.

    :param source:
    :param kwargs:
    :return:
    """
    return list(self.validate_iter(source, **kwargs))