Source code

Download source archive ↓

src/rdflib/plugins/parsers/trig.py

1from __future__ import annotations
2
3from typing import Any, MutableSequence
4
5from rdflib.graph import ConjunctiveGraph, Graph
6from rdflib.parser import InputSource, Parser
7
8from .notation3 import RDFSink, SinkParser
9
10
11def becauseSubGraph(*args, **kwargs):  # noqa: N802
12    pass
13
14
15class TrigSinkParser(SinkParser):
16    def directiveOrStatement(self, argstr: str, h: int) -> int:  # noqa: N802
17        # import pdb; pdb.set_trace()
18
19        i = self.skipSpace(argstr, h)
20        if i < 0:
21            return i  # EOF
22
23        j = self.graph(argstr, i)
24        if j >= 0:
25            return j
26
27        j = self.sparqlDirective(argstr, i)
28        if j >= 0:
29            return j
30
31        j = self.directive(argstr, i)
32        if j >= 0:
33            return self.checkDot(argstr, j)
34
35        j = self.statement(argstr, i)
36        if j >= 0:
37            return self.checkDot(argstr, j)
38
39        return j
40
41    def labelOrSubject(  # noqa: N802
42        self, argstr: str, i: int, res: MutableSequence[Any]
43    ) -> int:
44        j = self.skipSpace(argstr, i)
45        if j < 0:
46            return j  # eof
47        i = j
48
49        j = self.uri_ref2(argstr, i, res)
50        if j >= 0:
51            return j
52
53        if argstr[i] == "[":
54            j = self.skipSpace(argstr, i + 1)
55            if j < 0:
56                self.BadSyntax(argstr, i, "Expected ] got EOF")
57            if argstr[j] == "]":
58                res.append(self.blankNode())
59                return j + 1
60        return -1
61
62    def graph(self, argstr: str, i: int) -> int:
63        """
64        Parse trig graph, i.e.
65
66           <urn:graphname> = { .. triples .. }
67
68        return -1 if it doesn't look like a graph-decl
69        raise Exception if it looks like a graph, but isn't.
70        """
71
72        need_graphid = False
73        # import pdb; pdb.set_trace()
74        j = self.sparqlTok("GRAPH", argstr, i)  # optional GRAPH keyword
75        if j >= 0:
76            i = j
77            need_graphid = True
78
79        r: MutableSequence[Any] = []
80        j = self.labelOrSubject(argstr, i, r)
81        if j >= 0:
82            graph = r[0]
83            i = j
84        elif need_graphid:
85            self.BadSyntax(argstr, i, "GRAPH keyword must be followed by graph name")
86        else:
87            graph = self._store.graph.identifier  # hack
88
89        j = self.skipSpace(argstr, i)
90        if j < 0:
91            self.BadSyntax(argstr, i, "EOF found when expected graph")
92
93        if argstr[j : j + 1] == "=":  # optional = for legacy support
94            i = self.skipSpace(argstr, j + 1)
95            if i < 0:
96                self.BadSyntax(argstr, i, "EOF found when expecting '{'")
97        else:
98            i = j
99
100        if argstr[i : i + 1] != "{":
101            return -1  # the node wasn't part of a graph
102
103        j = i + 1
104
105        if self._context is not None:
106            self.BadSyntax(argstr, i, "Nested graphs are not allowed")
107
108        oldParentContext = self._parentContext  # noqa: N806
109        self._parentContext = self._context
110        reason2 = self._reason2
111        self._reason2 = becauseSubGraph
112        # type error: Incompatible types in assignment (expression has type "Graph", variable has type "Optional[Formula]")
113        self._context = self._store.newGraph(graph)  # type: ignore[assignment]
114
115        while 1:
116            i = self.skipSpace(argstr, j)
117            if i < 0:
118                self.BadSyntax(argstr, i, "needed '}', found end.")
119
120            if argstr[i : i + 1] == "}":
121                j = i + 1
122                break
123
124            j = self.directiveOrStatement(argstr, i)
125            if j < 0:
126                self.BadSyntax(argstr, i, "expected statement or '}'")
127
128        self._context = self._parentContext
129        self._reason2 = reason2
130        self._parentContext = oldParentContext
131        # res.append(subj.close())    # No use until closed
132        return j
133
134
135class TrigParser(Parser):
136    """
137    An RDFLib parser for TriG
138
139    """
140
141    def __init__(self):
142        pass
143
144    def parse(self, source: InputSource, graph: Graph, encoding: str = "utf-8") -> None:
145        if encoding not in [None, "utf-8"]:
146            raise Exception(
147                # type error: Unsupported left operand type for % ("Tuple[str, str]")
148                ("TriG files are always utf-8 encoded, ", "I was passed: %s")  # type: ignore[operator]
149                % encoding
150            )
151
152        # we're currently being handed a Graph, not a ConjunctiveGraph
153        assert graph.store.context_aware, "TriG Parser needs a context-aware store!"
154
155        conj_graph = ConjunctiveGraph(store=graph.store, identifier=graph.identifier)
156        conj_graph.default_context = graph  # TODO: CG __init__ should have a
157        # default_context arg
158        # TODO: update N3Processor so that it can use conj_graph as the sink
159        conj_graph.namespace_manager = graph.namespace_manager
160
161        sink = RDFSink(conj_graph)
162
163        baseURI = conj_graph.absolutize(  # noqa: N806
164            source.getPublicId() or source.getSystemId() or ""
165        )
166        p = TrigSinkParser(sink, baseURI=baseURI, turtle=True)
167
168        stream = source.getCharacterStream()  # try to get str stream first
169        if not stream:
170            # fallback to get the bytes stream
171            stream = source.getByteStream()
172        p.loadStream(stream)
173
174        for prefix, namespace in p._bindings.items():
175            conj_graph.bind(prefix, namespace)
176
177        # return ???