1
+ from __future__ import annotations
2
+
1
3
"""
2
4
Converting the 'parse-tree' output of pyparsing to a SPARQL Algebra expression
3
5
@@ -48,9 +50,7 @@ def OrderBy(p: CompValue, expr: List[CompValue]) -> CompValue:
48
50
return CompValue ("OrderBy" , p = p , expr = expr )
49
51
50
52
51
- def ToMultiSet (
52
- p : typing .Union [List [Dict [Variable , Identifier ]], CompValue ]
53
- ) -> CompValue :
53
+ def ToMultiSet (p : typing .Union [List [Dict [Variable , str ]], CompValue ]) -> CompValue :
54
54
return CompValue ("ToMultiSet" , p = p )
55
55
56
56
@@ -66,31 +66,35 @@ def Minus(p1: CompValue, p2: CompValue) -> CompValue:
66
66
return CompValue ("Minus" , p1 = p1 , p2 = p2 )
67
67
68
68
69
- def Graph (term , graph ) -> CompValue :
69
+ def Graph (term : Identifier , graph : CompValue ) -> CompValue :
70
70
return CompValue ("Graph" , term = term , p = graph )
71
71
72
72
73
- def BGP (triples = None ) -> CompValue :
73
+ def BGP (
74
+ triples : Optional [List [Tuple [Identifier , Identifier , Identifier ]]] = None
75
+ ) -> CompValue :
74
76
return CompValue ("BGP" , triples = triples or [])
75
77
76
78
77
79
def LeftJoin (p1 : CompValue , p2 : CompValue , expr ) -> CompValue :
78
80
return CompValue ("LeftJoin" , p1 = p1 , p2 = p2 , expr = expr )
79
81
80
82
81
- def Filter (expr , p : CompValue ) -> CompValue :
83
+ def Filter (expr : Expr , p : CompValue ) -> CompValue :
82
84
return CompValue ("Filter" , expr = expr , p = p )
83
85
84
86
85
- def Extend (p : CompValue , expr , var ) -> CompValue :
87
+ def Extend (
88
+ p : CompValue , expr : typing .Union [Identifier , Expr ], var : Variable
89
+ ) -> CompValue :
86
90
return CompValue ("Extend" , p = p , expr = expr , var = var )
87
91
88
92
89
- def Values (res ) -> CompValue :
93
+ def Values (res : List [ Dict [ Variable , str ]] ) -> CompValue :
90
94
return CompValue ("values" , res = res )
91
95
92
96
93
- def Project (p : CompValue , PV ) -> CompValue :
97
+ def Project (p : CompValue , PV : List [ Variable ] ) -> CompValue :
94
98
return CompValue ("Project" , p = p , PV = PV )
95
99
96
100
@@ -102,7 +106,7 @@ def _knownTerms(
102
106
triple : Tuple [Identifier , Identifier , Identifier ],
103
107
varsknown : Set [typing .Union [BNode , Variable ]],
104
108
varscount : Dict [Identifier , int ],
105
- ):
109
+ ) -> Tuple [ int , int , bool ] :
106
110
return (
107
111
len (
108
112
[
@@ -124,7 +128,7 @@ def reorderTriples(
124
128
ones with most bindings first
125
129
"""
126
130
127
- def _addvar (term , varsknown ):
131
+ def _addvar (term : str , varsknown : Set [ typing . Union [ Variable , BNode ]] ):
128
132
if isinstance (term , (Variable , BNode )):
129
133
varsknown .add (term )
130
134
@@ -180,20 +184,25 @@ def triples(
180
184
return reorderTriples ((l [x ], l [x + 1 ], l [x + 2 ]) for x in range (0 , len (l ), 3 )) # type: ignore[misc]
181
185
182
186
183
- def translatePName (p : typing .Union [CompValue , str ], prologue : Prologue ):
187
+ # type error: Missing return statement
188
+ def translatePName ( # type: ignore[return]
189
+ p : typing .Union [CompValue , str ], prologue : Prologue
190
+ ) -> Optional [Identifier ]:
184
191
"""
185
192
Expand prefixed/relative URIs
186
193
"""
187
194
if isinstance (p , CompValue ):
188
195
if p .name == "pname" :
189
- return prologue .absolutize (p )
196
+ # type error: Incompatible return value type (got "Union[CompValue, str, None]", expected "Optional[Identifier]")
197
+ return prologue .absolutize (p ) # type: ignore[return-value]
190
198
if p .name == "literal" :
191
199
# type error: Argument "datatype" to "Literal" has incompatible type "Union[CompValue, str, None]"; expected "Optional[str]"
192
200
return Literal (
193
201
p .string , lang = p .lang , datatype = prologue .absolutize (p .datatype ) # type: ignore[arg-type]
194
202
)
195
203
elif isinstance (p , URIRef ):
196
- return prologue .absolutize (p )
204
+ # type error: Incompatible return value type (got "Union[CompValue, str, None]", expected "Optional[Identifier]")
205
+ return prologue .absolutize (p ) # type: ignore[return-value]
197
206
198
207
199
208
@overload
@@ -253,8 +262,8 @@ def translatePath(p: typing.Union[CompValue, URIRef]) -> Optional["Path"]: # ty
253
262
254
263
255
264
def translateExists (
256
- e : typing .Union [Expr , Literal , Variable ]
257
- ) -> typing .Union [Expr , Literal , Variable ]:
265
+ e : typing .Union [Expr , Literal , Variable , URIRef ]
266
+ ) -> typing .Union [Expr , Literal , Variable , URIRef ]:
258
267
"""
259
268
Translate the graph pattern used by EXISTS and NOT EXISTS
260
269
http://www.w3.org/TR/sparql11-query/#sparqlCollectFilters
@@ -273,7 +282,7 @@ def _c(n):
273
282
return e
274
283
275
284
276
- def collectAndRemoveFilters (parts ) :
285
+ def collectAndRemoveFilters (parts : List [ CompValue ]) -> Optional [ Expr ] :
277
286
"""
278
287
279
288
FILTER expressions apply to the whole group graph pattern in which
@@ -294,7 +303,8 @@ def collectAndRemoveFilters(parts):
294
303
i += 1
295
304
296
305
if filters :
297
- return and_ (* filters )
306
+ # type error: Argument 1 to "and_" has incompatible type "*List[Union[Expr, Literal, Variable]]"; expected "Expr"
307
+ return and_ (* filters ) # type: ignore[arg-type]
298
308
299
309
return None
300
310
@@ -380,7 +390,7 @@ def translateGroupGraphPattern(graphPattern: CompValue) -> CompValue:
380
390
381
391
382
392
class StopTraversal (Exception ): # noqa: N818
383
- def __init__ (self , rv ):
393
+ def __init__ (self , rv : bool ):
384
394
self .rv = rv
385
395
386
396
@@ -444,7 +454,7 @@ def traverse(
444
454
visitPre : Callable [[Any ], Any ] = lambda n : None ,
445
455
visitPost : Callable [[Any ], Any ] = lambda n : None ,
446
456
complete : Optional [bool ] = None ,
447
- ):
457
+ ) -> Any :
448
458
"""
449
459
Traverse tree, visit each node with visit function
450
460
visit function may raise StopTraversal to stop traversal
@@ -504,7 +514,7 @@ def _findVars(x, res: Set[Variable]) -> Optional[CompValue]: # type: ignore[ret
504
514
return x
505
515
506
516
507
- def _addVars (x , children ) -> Set [Variable ]:
517
+ def _addVars (x , children : List [ Set [ Variable ]] ) -> Set [Variable ]:
508
518
"""
509
519
find which variables may be bound by this part of the query
510
520
"""
@@ -549,7 +559,7 @@ def _sample(e: typing.Union[CompValue, List[Expr], Expr, List[str], Variable], v
549
559
return CompValue ("Aggregate_Sample" , vars = e )
550
560
551
561
552
- def _simplifyFilters (e ) :
562
+ def _simplifyFilters (e : Any ) -> Any :
553
563
if isinstance (e , Expr ):
554
564
return simplifyFilters (e )
555
565
@@ -592,11 +602,11 @@ def translateAggregates(
592
602
593
603
def translateValues (
594
604
v : CompValue ,
595
- ) -> typing .Union [List [Dict [Variable , Identifier ]], CompValue ]:
605
+ ) -> typing .Union [List [Dict [Variable , str ]], CompValue ]:
596
606
# if len(v.var)!=len(v.value):
597
607
# raise Exception("Unmatched vars and values in ValueClause: "+str(v))
598
608
599
- res : List [Dict [Variable , Identifier ]] = []
609
+ res : List [Dict [Variable , str ]] = []
600
610
if not v .var :
601
611
return res
602
612
if not v .value :
@@ -722,7 +732,7 @@ def translate(q: CompValue) -> Tuple[CompValue, List[Variable]]:
722
732
723
733
724
734
# type error: Missing return statement
725
- def simplify (n ) -> Optional [CompValue ]: # type: ignore[return]
735
+ def simplify (n : Any ) -> Optional [CompValue ]: # type: ignore[return]
726
736
"""Remove joins to empty BGPs"""
727
737
if isinstance (n , CompValue ):
728
738
if n .name == "Join" :
@@ -735,7 +745,7 @@ def simplify(n) -> Optional[CompValue]: # type: ignore[return]
735
745
return n
736
746
737
747
738
- def analyse (n , children ) :
748
+ def analyse (n : Any , children : Any ) -> bool :
739
749
"""
740
750
Some things can be lazily joined.
741
751
This propegates whether they can up the tree
@@ -757,7 +767,7 @@ def analyse(n, children):
757
767
def translatePrologue (
758
768
p : ParseResults ,
759
769
base : Optional [str ],
760
- initNs : Optional [Mapping [str , str ]] = None ,
770
+ initNs : Optional [Mapping [str , Any ]] = None ,
761
771
prologue : Optional [Prologue ] = None ,
762
772
) -> Prologue :
763
773
@@ -780,7 +790,12 @@ def translatePrologue(
780
790
return prologue
781
791
782
792
783
- def translateQuads (quads : CompValue ):
793
+ def translateQuads (
794
+ quads : CompValue ,
795
+ ) -> Tuple [
796
+ List [Tuple [Identifier , Identifier , Identifier ]],
797
+ DefaultDict [str , List [Tuple [Identifier , Identifier , Identifier ]]],
798
+ ]:
784
799
if quads .triples :
785
800
alltriples = triples (quads .triples )
786
801
else :
@@ -825,7 +840,7 @@ def translateUpdate1(u: CompValue, prologue: Prologue) -> CompValue:
825
840
def translateUpdate (
826
841
q : CompValue ,
827
842
base : Optional [str ] = None ,
828
- initNs : Optional [Mapping [str , str ]] = None ,
843
+ initNs : Optional [Mapping [str , Any ]] = None ,
829
844
) -> Update :
830
845
"""
831
846
Returns a list of SPARQL Update Algebra expressions
@@ -854,7 +869,7 @@ def translateUpdate(
854
869
def translateQuery (
855
870
q : ParseResults ,
856
871
base : Optional [str ] = None ,
857
- initNs : Optional [Mapping [str , str ]] = None ,
872
+ initNs : Optional [Mapping [str , Any ]] = None ,
858
873
) -> Query :
859
874
"""
860
875
Translate a query-parsetree to a SPARQL Algebra Expression
@@ -901,7 +916,7 @@ def translateAlgebra(query_algebra: Query) -> str:
901
916
"""
902
917
import os
903
918
904
- def overwrite (text ):
919
+ def overwrite (text : str ):
905
920
file = open ("query.txt" , "w+" )
906
921
file .write (text )
907
922
file .close ()
@@ -938,19 +953,26 @@ def find_nth(haystack, needle, n):
938
953
with open ("query.txt" , "w" ) as file :
939
954
file .write (filedata )
940
955
941
- aggr_vars = collections .defaultdict (list ) # type: dict
956
+ aggr_vars : DefaultDict [ Identifier , List [ Identifier ]] = collections .defaultdict (list )
942
957
943
- def convert_node_arg (node_arg ):
958
+ def convert_node_arg (
959
+ node_arg : typing .Union [Identifier , CompValue , Expr , str ]
960
+ ) -> str :
944
961
if isinstance (node_arg , Identifier ):
945
962
if node_arg in aggr_vars .keys ():
946
- grp_var = aggr_vars [node_arg ].pop (0 ).n3 ()
963
+ # type error: "Identifier" has no attribute "n3"
964
+ grp_var = aggr_vars [node_arg ].pop (0 ).n3 () # type: ignore[attr-defined]
947
965
return grp_var
948
966
else :
949
- return node_arg .n3 ()
967
+ # type error: "Identifier" has no attribute "n3"
968
+ return node_arg .n3 () # type: ignore[attr-defined]
950
969
elif isinstance (node_arg , CompValue ):
951
970
return "{" + node_arg .name + "}"
952
- elif isinstance (node_arg , Expr ):
953
- return "{" + node_arg .name + "}"
971
+ # type error notes: this is because Expr is a subclass of CompValue
972
+ # type error: Subclass of "str" and "Expr" cannot exist: would have incompatible method signatures
973
+ elif isinstance (node_arg , Expr ): # type: ignore[unreachable]
974
+ # type error: Statement is unreachable
975
+ return "{" + node_arg .name + "}" # type: ignore[unreachable]
954
976
elif isinstance (node_arg , str ):
955
977
return node_arg
956
978
else :
@@ -1529,7 +1551,7 @@ def sparql_query_text(node):
1529
1551
return query_from_algebra
1530
1552
1531
1553
1532
- def pprintAlgebra (q ):
1554
+ def pprintAlgebra (q ) -> None :
1533
1555
def pp (p , ind = " " ):
1534
1556
# if isinstance(p, list):
1535
1557
# print "[ "
0 commit comments