-
Notifications
You must be signed in to change notification settings - Fork 546
/
notation3.py
executable file
·1977 lines (1640 loc) · 61.7 KB
/
notation3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
notation3.py - Standalone Notation3 Parser
Derived from CWM, the Closed World Machine
Authors of the original suite:
* Dan Connolly <@@>
* Tim Berners-Lee <@@>
* Yosi Scharf <@@>
* Joseph M. Reagle Jr. <reagle@w3.org>
* Rich Salz <rsalz@zolera.com>
http://www.w3.org/2000/10/swap/notation3.py
Copyright 2000-2007, World Wide Web Consortium.
Copyright 2001, MIT.
Copyright 2001, Zolera Systems Inc.
License: W3C Software License
http://www.w3.org/Consortium/Legal/copyright-software
Modified by Sean B. Palmer
Copyright 2007, Sean B. Palmer.
Modified to work with rdflib by Gunnar Aastrand Grimnes
Copyright 2010, Gunnar A. Grimnes
"""
import codecs
import os
import re
import sys
# importing typing for `typing.List` because `List`` is used for something else
import typing
from decimal import Decimal
from typing import IO, TYPE_CHECKING, Any, Callable, Dict, Optional, TypeVar, Union
from uuid import uuid4
from rdflib.compat import long_type
from rdflib.exceptions import ParserError
from rdflib.graph import ConjunctiveGraph, Graph, QuotedGraph
from rdflib.term import (
_XSD_PFX,
BNode,
Identifier,
Literal,
Node,
URIRef,
Variable,
_unique_id,
)
__all__ = [
"BadSyntax",
"N3Parser",
"TurtleParser",
"splitFragP",
"join",
"base",
"runNamespace",
"uniqueURI",
"hexify",
]
from rdflib.parser import Parser
if TYPE_CHECKING:
from rdflib.parser import InputSource
AnyT = TypeVar("AnyT")
def splitFragP(uriref, punct=0):
"""split a URI reference before the fragment
Punctuation is kept.
e.g.
>>> splitFragP("abc#def")
('abc', '#def')
>>> splitFragP("abcdef")
('abcdef', '')
"""
i = uriref.rfind("#")
if i >= 0:
return uriref[:i], uriref[i:]
else:
return uriref, ""
def join(here, there):
"""join an absolute URI and URI reference
(non-ascii characters are supported/doctested;
haven't checked the details of the IRI spec though)
``here`` is assumed to be absolute.
``there`` is URI reference.
>>> join('http://example/x/y/z', '../abc')
'http://example/x/abc'
Raise ValueError if there uses relative path
syntax but here has no hierarchical path.
>>> join('mid:foo@example', '../foo') # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
raise ValueError(here)
ValueError: Base <mid:foo@example> has no slash
after colon - with relative '../foo'.
>>> join('http://example/x/y/z', '')
'http://example/x/y/z'
>>> join('mid:foo@example', '#foo')
'mid:foo@example#foo'
We grok IRIs
>>> len(u'Andr\\xe9')
5
>>> join('http://example.org/', u'#Andr\\xe9')
u'http://example.org/#Andr\\xe9'
"""
# assert(here.find("#") < 0), \
# "Base may not contain hash: '%s'" % here # why must caller splitFrag?
slashl = there.find("/")
colonl = there.find(":")
# join(base, 'foo:/') -- absolute
if colonl >= 0 and (slashl < 0 or colonl < slashl):
return there
bcolonl = here.find(":")
assert bcolonl >= 0, (
"Base uri '%s' is not absolute" % here
) # else it's not absolute
path, frag = splitFragP(there)
if not path:
return here + frag
# join('mid:foo@example', '../foo') bzzt
if here[bcolonl + 1 : bcolonl + 2] != "/":
raise ValueError(
"Base <%s> has no slash after "
"colon - with relative '%s'." % (here, there)
)
if here[bcolonl + 1 : bcolonl + 3] == "//":
bpath = here.find("/", bcolonl + 3)
else:
bpath = bcolonl + 1
# join('http://xyz', 'foo')
if bpath < 0:
bpath = len(here)
here = here + "/"
# join('http://xyz/', '//abc') => 'http://abc'
if there[:2] == "//":
return here[: bcolonl + 1] + there
# join('http://xyz/', '/abc') => 'http://xyz/abc'
if there[:1] == "/":
return here[:bpath] + there
slashr = here.rfind("/")
while 1:
if path[:2] == "./":
path = path[2:]
if path == ".":
path = ""
elif path[:3] == "../" or path == "..":
path = path[3:]
i = here.rfind("/", bpath, slashr)
if i >= 0:
here = here[: i + 1]
slashr = i
else:
break
return here[: slashr + 1] + path + frag
def base():
"""The base URI for this process - the Web equiv of cwd
Relative or absolute unix-standard filenames parsed relative to
this yield the URI of the file.
If we had a reliable way of getting a computer name,
we should put it in the hostname just to prevent ambiguity
"""
# return "file://" + hostname + os.getcwd() + "/"
return "file://" + _fixslash(os.getcwd()) + "/"
def _fixslash(s):
"""Fix windowslike filename to unixlike - (#ifdef WINDOWS)"""
s = s.replace("\\", "/")
if s[0] != "/" and s[1] == ":":
s = s[2:] # @@@ Hack when drive letter present
return s
CONTEXT = 0
PRED = 1
SUBJ = 2
OBJ = 3
PARTS = PRED, SUBJ, OBJ
ALL4 = CONTEXT, PRED, SUBJ, OBJ
SYMBOL = 0
FORMULA = 1
LITERAL = 2
LITERAL_DT = 21
LITERAL_LANG = 22
ANONYMOUS = 3
XMLLITERAL = 25
Logic_NS = "http://www.w3.org/2000/10/swap/log#"
NODE_MERGE_URI = Logic_NS + "is" # Pseudo-property indicating node merging
forSomeSym = Logic_NS + "forSome"
forAllSym = Logic_NS + "forAll"
RDF_type_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
RDF_NS_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
OWL_NS = "http://www.w3.org/2002/07/owl#"
DAML_sameAs_URI = OWL_NS + "sameAs"
parsesTo_URI = Logic_NS + "parsesTo"
RDF_spec = "http://www.w3.org/TR/REC-rdf-syntax/"
List_NS = RDF_NS_URI # From 20030808
_Old_Logic_NS = "http://www.w3.org/2000/10/swap/log.n3#"
N3_first = (SYMBOL, List_NS + "first")
N3_rest = (SYMBOL, List_NS + "rest")
N3_li = (SYMBOL, List_NS + "li")
N3_nil = (SYMBOL, List_NS + "nil")
N3_List = (SYMBOL, List_NS + "List")
N3_Empty = (SYMBOL, List_NS + "Empty")
runNamespaceValue = None
def runNamespace():
"""Returns a URI suitable as a namespace for run-local objects"""
# @@@ include hostname (privacy?) (hash it?)
global runNamespaceValue
if runNamespaceValue is None:
runNamespaceValue = join(base(), _unique_id()) + "#"
return runNamespaceValue
nextu = 0
def uniqueURI():
"""A unique URI"""
global nextu
nextu += 1
return runNamespace() + "u_" + str(nextu)
tracking = False
chatty_flag = 50
# from why import BecauseOfData, becauseSubexpression
def BecauseOfData(*args, **kargs):
# print args, kargs
pass
def becauseSubexpression(*args, **kargs):
# print args, kargs
pass
N3_forSome_URI = forSomeSym
N3_forAll_URI = forAllSym
# Magic resources we know about
ADDED_HASH = "#" # Stop where we use this in case we want to remove it!
# This is the hash on namespace URIs
RDF_type = (SYMBOL, RDF_type_URI)
DAML_sameAs = (SYMBOL, DAML_sameAs_URI)
LOG_implies_URI = "http://www.w3.org/2000/10/swap/log#implies"
BOOLEAN_DATATYPE = _XSD_PFX + "boolean"
DECIMAL_DATATYPE = _XSD_PFX + "decimal"
DOUBLE_DATATYPE = _XSD_PFX + "double"
FLOAT_DATATYPE = _XSD_PFX + "float"
INTEGER_DATATYPE = _XSD_PFX + "integer"
option_noregen = 0 # If set, do not regenerate genids on output
# @@ I18n - the notname chars need extending for well known unicode non-text
# characters. The XML spec switched to assuming unknown things were name
# characters.
# _namechars = string.lowercase + string.uppercase + string.digits + '_-'
_notQNameChars = set("\t\r\n !\"#$&'()*,+/;<=>?@[\\]^`{|}~") # else valid qname :-/
_notKeywordsChars = _notQNameChars | {"."}
_notNameChars = _notQNameChars | {":"} # Assume anything else valid name :-/
_rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
hexChars = set("ABCDEFabcdef0123456789")
escapeChars = set("(_~.-!$&'()*+,;=/?#@%)") # valid for \ escapes in localnames
numberChars = set("0123456789-")
numberCharsPlus = numberChars | {"+", "."}
def unicodeExpand(m):
try:
return chr(int(m.group(1), 16))
except:
raise Exception("Invalid unicode code point: " + m.group(1))
unicodeEscape4 = re.compile(r"\\u([0-9a-fA-F]{4})")
unicodeEscape8 = re.compile(r"\\U([0-9a-fA-F]{8})")
N3CommentCharacter = "#" # For unix script # ! compatibility
# Parse string to sink
#
# Regular expressions:
eol = re.compile(r"[ \t]*(#[^\n]*)?\r?\n") # end of line, poss. w/comment
eof = re.compile(r"[ \t]*(#[^\n]*)?$") # end of file, poss. w/comment
ws = re.compile(r"[ \t]*") # Whitespace not including NL
signed_integer = re.compile(r"[-+]?[0-9]+") # integer
integer_syntax = re.compile(r"[-+]?[0-9]+")
decimal_syntax = re.compile(r"[-+]?[0-9]*\.[0-9]+")
exponent_syntax = re.compile(
r"[-+]?(?:[0-9]+\.[0-9]*|\.[0-9]+|[0-9]+)(?:e|E)[-+]?[0-9]+"
)
digitstring = re.compile(r"[0-9]+") # Unsigned integer
interesting = re.compile(r"""[\\\r\n\"\']""")
langcode = re.compile(r"[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*")
class SinkParser:
def __init__(
self,
store: "RDFSink",
openFormula: Optional["Formula"] = None,
thisDoc: str = "",
baseURI: Optional[str] = None,
genPrefix: str = "",
why: Optional[Callable[[], None]] = None,
turtle: bool = False,
):
"""note: namespace names should *not* end in # ;
the # will get added during qname processing"""
self._bindings = {}
if thisDoc != "":
assert ":" in thisDoc, "Document URI not absolute: <%s>" % thisDoc
self._bindings[""] = thisDoc + "#" # default
self._store = store
if genPrefix:
# TODO FIXME: there is no function named setGenPrefix
store.setGenPrefix(genPrefix) # type: ignore[attr-defined] # pass it on
self._thisDoc = thisDoc
self.lines = 0 # for error handling
self.startOfLine = 0 # For calculating character number
self._genPrefix = genPrefix
self.keywords = ["a", "this", "bind", "has", "is", "of", "true", "false"]
self.keywordsSet = 0 # Then only can others be considered qnames
self._anonymousNodes: Dict[str, Node] = {}
# Dict of anon nodes already declared ln: Term
self._variables: Dict[Identifier, Identifier] = {}
self._parentVariables: Dict[Identifier, Identifier] = {}
self._reason = why # Why the parser was asked to parse this
self.turtle = turtle # raise exception when encountering N3 extensions
# Turtle allows single or double quotes around strings, whereas N3
# only allows double quotes.
self.string_delimiters = ('"', "'") if turtle else ('"',)
self._reason2 = None # Why these triples
# was: diag.tracking
if tracking:
self._reason2 = BecauseOfData(
store.newSymbol(thisDoc), because=self._reason
)
self._baseURI: Optional[str]
if baseURI:
self._baseURI = baseURI
else:
if thisDoc:
self._baseURI = thisDoc
else:
self._baseURI = None
assert not self._baseURI or ":" in self._baseURI
if not self._genPrefix:
if self._thisDoc:
self._genPrefix = self._thisDoc + "#_g"
else:
self._genPrefix = uniqueURI()
self._formula: Formula
if openFormula is None and not turtle:
if self._thisDoc:
# TODO FIXME: store.newFormula does not take any arguments
self._formula = store.newFormula(thisDoc + "#_formula") # type: ignore[call-arg]
else:
self._formula = store.newFormula()
else:
self._formula = openFormula # type: ignore[assignment]
self._context = self._formula
self._parentContext: Optional[Formula] = None
def here(self, i: int) -> str:
"""String generated from position in file
This is for repeatability when referring people to bnodes in a document.
This has diagnostic uses less formally, as it should point one to which
bnode the arbitrary identifier actually is. It gives the
line and character number of the '[' charcacter or path character
which introduced the blank node. The first blank node is boringly
_L1C1. It used to be used only for tracking, but for tests in general
it makes the canonical ordering of bnodes repeatable."""
return "%s_L%iC%i" % (self._genPrefix, self.lines, i - self.startOfLine + 1)
def formula(self):
return self._formula
def loadStream(self, stream: Union[IO[str], IO[bytes]]) -> Optional["Formula"]:
return self.loadBuf(stream.read()) # Not ideal
def loadBuf(self, buf: Union[str, bytes]):
"""Parses a buffer and returns its top level formula"""
self.startDoc()
self.feed(buf)
return self.endDoc() # self._formula
def feed(self, octets: Union[str, bytes]):
"""Feed an octet stream to the parser
if BadSyntax is raised, the string
passed in the exception object is the
remainder after any statements have been parsed.
So if there is more data to feed to the
parser, it should be straightforward to recover."""
if not isinstance(octets, str):
s = octets.decode("utf-8")
# NB already decoded, so \ufeff
if len(s) > 0 and s[0] == codecs.BOM_UTF8.decode("utf-8"):
s = s[1:]
else:
s = octets
i = 0
while i >= 0:
j = self.skipSpace(s, i)
if j < 0:
return
i = self.directiveOrStatement(s, j)
if i < 0:
# print("# next char: %s" % s[j])
self.BadSyntax(s, j, "expected directive or statement")
def directiveOrStatement(self, argstr: str, h: int) -> int:
i = self.skipSpace(argstr, h)
if i < 0:
return i # EOF
if self.turtle:
j = self.sparqlDirective(argstr, i)
if j >= 0:
return j
j = self.directive(argstr, i)
if j >= 0:
return self.checkDot(argstr, j)
j = self.statement(argstr, i)
if j >= 0:
return self.checkDot(argstr, j)
return j
# @@I18N
# _namechars = string.lowercase + string.uppercase + string.digits + '_-'
def tok(self, tok: str, argstr: str, i: int, colon: bool = False):
"""Check for keyword. Space must have been stripped on entry and
we must not be at end of file.
if colon, then keyword followed by colon is ok
(@prefix:<blah> is ok, rdf:type shortcut a must be followed by ws)
"""
assert tok[0] not in _notNameChars # not for punctuation
if argstr[i] == "@":
i += 1
else:
if tok not in self.keywords:
return -1 # No, this has neither keywords declaration nor "@"
i_plus_len_tok = i + len(tok)
if (
argstr[i:i_plus_len_tok] == tok
and (argstr[i_plus_len_tok] in _notKeywordsChars)
or (colon and argstr[i_plus_len_tok] == ":")
):
return i_plus_len_tok
else:
return -1
def sparqlTok(self, tok: str, argstr: str, i: int) -> int:
"""Check for SPARQL keyword. Space must have been stripped on entry
and we must not be at end of file.
Case insensitive and not preceded by @
"""
assert tok[0] not in _notNameChars # not for punctuation
len_tok = len(tok)
if argstr[i : i + len_tok].lower() == tok.lower() and (
argstr[i + len_tok] in _notQNameChars
):
i += len_tok
return i
else:
return -1
def directive(self, argstr: str, i: int) -> int:
j = self.skipSpace(argstr, i)
if j < 0:
return j # eof
res: typing.List[Any] = []
j = self.tok("bind", argstr, i) # implied "#". Obsolete.
if j > 0:
self.BadSyntax(argstr, i, "keyword bind is obsolete: use @prefix")
j = self.tok("keywords", argstr, i)
if j > 0:
if self.turtle:
self.BadSyntax(argstr, i, "Found 'keywords' when in Turtle mode.")
i = self.commaSeparatedList(argstr, j, res, self.bareWord)
if i < 0:
self.BadSyntax(
argstr, i, "'@keywords' needs comma separated list of words"
)
self.setKeywords(res[:])
return i
j = self.tok("forAll", argstr, i)
if j > 0:
if self.turtle:
self.BadSyntax(argstr, i, "Found 'forAll' when in Turtle mode.")
i = self.commaSeparatedList(argstr, j, res, self.uri_ref2)
if i < 0:
self.BadSyntax(argstr, i, "Bad variable list after @forAll")
for x in res:
# self._context.declareUniversal(x)
if x not in self._variables or x in self._parentVariables:
self._variables[x] = self._context.newUniversal(x)
return i
j = self.tok("forSome", argstr, i)
if j > 0:
if self.turtle:
self.BadSyntax(argstr, i, "Found 'forSome' when in Turtle mode.")
i = self.commaSeparatedList(argstr, j, res, self.uri_ref2)
if i < 0:
self.BadSyntax(argstr, i, "Bad variable list after @forSome")
for x in res:
self._context.declareExistential(x)
return i
j = self.tok("prefix", argstr, i, colon=True) # no implied "#"
if j >= 0:
t: typing.List[Any] = []
i = self.qname(argstr, j, t)
if i < 0:
self.BadSyntax(argstr, j, "expected qname after @prefix")
j = self.uri_ref2(argstr, i, t)
if j < 0:
self.BadSyntax(argstr, i, "expected <uriref> after @prefix _qname_")
ns = self.uriOf(t[1])
if self._baseURI:
ns = join(self._baseURI, ns)
elif ":" not in ns:
self.BadSyntax(
argstr,
j,
f"With no base URI, cannot use relative URI in @prefix <{ns}>",
)
assert ":" in ns # must be absolute
self._bindings[t[0][0]] = ns
self.bind(t[0][0], hexify(ns))
return j
j = self.tok("base", argstr, i) # Added 2007/7/7
if j >= 0:
t = []
i = self.uri_ref2(argstr, j, t)
if i < 0:
self.BadSyntax(argstr, j, "expected <uri> after @base ")
ns = self.uriOf(t[0])
if self._baseURI:
ns = join(self._baseURI, ns)
else:
self.BadSyntax(
argstr,
j,
"With no previous base URI, cannot use "
+ "relative URI in @base <"
+ ns
+ ">",
)
assert ":" in ns # must be absolute
self._baseURI = ns
return i
return -1 # Not a directive, could be something else.
def sparqlDirective(self, argstr: str, i: int):
"""
turtle and trig support BASE/PREFIX without @ and without
terminating .
"""
j = self.skipSpace(argstr, i)
if j < 0:
return j # eof
j = self.sparqlTok("PREFIX", argstr, i)
if j >= 0:
t: typing.List[Any] = []
i = self.qname(argstr, j, t)
if i < 0:
self.BadSyntax(argstr, j, "expected qname after @prefix")
j = self.uri_ref2(argstr, i, t)
if j < 0:
self.BadSyntax(argstr, i, "expected <uriref> after @prefix _qname_")
ns = self.uriOf(t[1])
if self._baseURI:
ns = join(self._baseURI, ns)
elif ":" not in ns:
self.BadSyntax(
argstr,
j,
"With no base URI, cannot use "
+ "relative URI in @prefix <"
+ ns
+ ">",
)
assert ":" in ns # must be absolute
self._bindings[t[0][0]] = ns
self.bind(t[0][0], hexify(ns))
return j
j = self.sparqlTok("BASE", argstr, i)
if j >= 0:
t = []
i = self.uri_ref2(argstr, j, t)
if i < 0:
self.BadSyntax(argstr, j, "expected <uri> after @base ")
ns = self.uriOf(t[0])
if self._baseURI:
ns = join(self._baseURI, ns)
else:
self.BadSyntax(
argstr,
j,
"With no previous base URI, cannot use "
+ "relative URI in @base <"
+ ns
+ ">",
)
assert ":" in ns # must be absolute
self._baseURI = ns
return i
return -1 # Not a directive, could be something else.
def bind(self, qn: str, uri: bytes) -> None:
assert isinstance(uri, bytes), "Any unicode must be %x-encoded already"
if qn == "":
self._store.setDefaultNamespace(uri)
else:
self._store.bind(qn, uri)
def setKeywords(self, k: Optional[typing.List[str]]):
"""Takes a list of strings"""
if k is None:
self.keywordsSet = 0
else:
self.keywords = k
self.keywordsSet = 1
def startDoc(self) -> None:
# was: self._store.startDoc()
self._store.startDoc(self._formula)
def endDoc(self) -> Optional["Formula"]:
"""Signal end of document and stop parsing. returns formula"""
self._store.endDoc(self._formula) # don't canonicalize yet
return self._formula
def makeStatement(self, quadruple):
# $$$$$$$$$$$$$$$$$$$$$
# print "# Parser output: ", `quadruple`
self._store.makeStatement(quadruple, why=self._reason2)
def statement(self, argstr: str, i: int) -> int:
r: typing.List[Any] = []
i = self.object(argstr, i, r) # Allow literal for subject - extends RDF
if i < 0:
return i
j = self.property_list(argstr, i, r[0])
if j < 0:
self.BadSyntax(argstr, i, "expected propertylist")
return j
def subject(self, argstr: str, i: int, res: typing.List[Any]) -> int:
return self.item(argstr, i, res)
def verb(self, argstr: str, i: int, res: typing.List[Any]) -> int:
"""has _prop_
is _prop_ of
a
=
_prop_
>- prop ->
<- prop -<
_operator_"""
j = self.skipSpace(argstr, i)
if j < 0:
return j # eof
r: typing.List[Any] = []
j = self.tok("has", argstr, i)
if j >= 0:
if self.turtle:
self.BadSyntax(argstr, i, "Found 'has' keyword in Turtle mode")
i = self.prop(argstr, j, r)
if i < 0:
self.BadSyntax(argstr, j, "expected property after 'has'")
res.append(("->", r[0]))
return i
j = self.tok("is", argstr, i)
if j >= 0:
if self.turtle:
self.BadSyntax(argstr, i, "Found 'is' keyword in Turtle mode")
i = self.prop(argstr, j, r)
if i < 0:
self.BadSyntax(argstr, j, "expected <property> after 'is'")
j = self.skipSpace(argstr, i)
if j < 0:
self.BadSyntax(
argstr, i, "End of file found, expected property after 'is'"
)
i = j
j = self.tok("of", argstr, i)
if j < 0:
self.BadSyntax(argstr, i, "expected 'of' after 'is' <prop>")
res.append(("<-", r[0]))
return j
j = self.tok("a", argstr, i)
if j >= 0:
res.append(("->", RDF_type))
return j
if argstr[i : i + 2] == "<=":
if self.turtle:
self.BadSyntax(argstr, i, "Found '<=' in Turtle mode. ")
res.append(("<-", self._store.newSymbol(Logic_NS + "implies")))
return i + 2
if argstr[i] == "=":
if self.turtle:
self.BadSyntax(argstr, i, "Found '=' in Turtle mode")
if argstr[i + 1] == ">":
res.append(("->", self._store.newSymbol(Logic_NS + "implies")))
return i + 2
res.append(("->", DAML_sameAs))
return i + 1
if argstr[i : i + 2] == ":=":
if self.turtle:
self.BadSyntax(argstr, i, "Found ':=' in Turtle mode")
# patch file relates two formulae, uses this @@ really?
res.append(("->", Logic_NS + "becomes"))
return i + 2
j = self.prop(argstr, i, r)
if j >= 0:
res.append(("->", r[0]))
return j
if argstr[i : i + 2] == ">-" or argstr[i : i + 2] == "<-":
self.BadSyntax(argstr, j, ">- ... -> syntax is obsolete.")
return -1
def prop(self, argstr: str, i: int, res):
return self.item(argstr, i, res)
def item(self, argstr: str, i, res):
return self.path(argstr, i, res)
def blankNode(self, uri=None):
return self._store.newBlankNode(self._context, uri, why=self._reason2)
def path(self, argstr: str, i: int, res):
"""Parse the path production."""
j = self.nodeOrLiteral(argstr, i, res)
if j < 0:
return j # nope
while argstr[j] in {"!", "^"}: # no spaces, must follow exactly (?)
ch = argstr[j]
subj = res.pop()
obj = self.blankNode(uri=self.here(j))
j = self.node(argstr, j + 1, res)
if j < 0:
self.BadSyntax(argstr, j, "EOF found in middle of path syntax")
pred = res.pop()
if ch == "^": # Reverse traverse
self.makeStatement((self._context, pred, obj, subj))
else:
self.makeStatement((self._context, pred, subj, obj))
res.append(obj)
return j
def anonymousNode(self, ln: str):
"""Remember or generate a term for one of these _: anonymous nodes"""
term = self._anonymousNodes.get(ln, None)
if term is not None:
return term
term = self._store.newBlankNode(self._context, why=self._reason2)
self._anonymousNodes[ln] = term
return term
def node(self, argstr: str, i: int, res, subjectAlready=None):
"""Parse the <node> production.
Space is now skipped once at the beginning
instead of in multiple calls to self.skipSpace().
"""
subj = subjectAlready
j = self.skipSpace(argstr, i)
if j < 0:
return j # eof
i = j
ch = argstr[i] # Quick 1-character checks first:
if ch == "[":
bnodeID = self.here(i)
j = self.skipSpace(argstr, i + 1)
if j < 0:
self.BadSyntax(argstr, i, "EOF after '['")
# Hack for "is" binding name to anon node
if argstr[j] == "=":
if self.turtle:
self.BadSyntax(
argstr, j, "Found '[=' or '[ =' when in turtle mode."
)
i = j + 1
objs: typing.List[Any] = []
j = self.objectList(argstr, i, objs)
if j >= 0:
subj = objs[0]
if len(objs) > 1:
for obj in objs:
self.makeStatement((self._context, DAML_sameAs, subj, obj))
j = self.skipSpace(argstr, j)
if j < 0:
self.BadSyntax(
argstr, i, "EOF when objectList expected after [ = "
)
if argstr[j] == ";":
j += 1
else:
self.BadSyntax(argstr, i, "objectList expected after [= ")
if subj is None:
subj = self.blankNode(uri=bnodeID)
i = self.property_list(argstr, j, subj)
if i < 0:
self.BadSyntax(argstr, j, "property_list expected")
j = self.skipSpace(argstr, i)
if j < 0:
self.BadSyntax(
argstr, i, "EOF when ']' expected after [ <propertyList>"
)
if argstr[j] != "]":
self.BadSyntax(argstr, j, "']' expected")
res.append(subj)
return j + 1
if not self.turtle and ch == "{":
# if self.turtle:
# self.BadSyntax(argstr, i,
# "found '{' while in Turtle mode, Formulas not supported!")
ch2 = argstr[i + 1]
if ch2 == "$":
# a set
i += 1
j = i + 1
List = []
first_run = True
while 1:
i = self.skipSpace(argstr, j)
if i < 0:
self.BadSyntax(argstr, i, "needed '$}', found end.")
if argstr[i : i + 2] == "$}":
j = i + 2
break
if not first_run:
if argstr[i] == ",":
i += 1
else:
self.BadSyntax(argstr, i, "expected: ','")
else:
first_run = False
item: typing.List[Any] = []
j = self.item(argstr, i, item) # @@@@@ should be path, was object
if j < 0:
self.BadSyntax(argstr, i, "expected item in set or '$}'")
List.append(self._store.intern(item[0]))
res.append(self._store.newSet(List, self._context))
return j
else:
# parse a formula
j = i + 1
oldParentContext = self._parentContext
self._parentContext = self._context
parentAnonymousNodes = self._anonymousNodes
grandParentVariables = self._parentVariables
self._parentVariables = self._variables
self._anonymousNodes = {}
self._variables = self._variables.copy()
reason2 = self._reason2
self._reason2 = becauseSubexpression
if subj is None:
subj = self._store.newFormula()
self._context = subj
while 1:
i = self.skipSpace(argstr, j)
if i < 0:
self.BadSyntax(argstr, i, "needed '}', found end.")