File size: 23,940 Bytes
e1f5446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
diff --git a/rdflib/plugins/sparql/parser.py b/rdflib/plugins/sparql/parser.py
index 789d0761..beb7aa6f 100644
--- a/rdflib/plugins/sparql/parser.py
+++ b/rdflib/plugins/sparql/parser.py
@@ -24,14 +24,13 @@ from pyparsing import (
     Regex,
     Suppress,
     ZeroOrMore,
-    delimitedList,
-    restOfLine,
 )
 
 import rdflib
 from rdflib.compat import decodeUnicodeEscape
 
 from . import operators as op
+from .pyparsing_compat import DelimitedList, combine_join_kwargs, rest_of_line
 from .parserutils import Comp, CompValue, Param, ParamList
 
 # from pyparsing import Keyword as CaseSensitiveKeyword
@@ -89,7 +88,7 @@ def expandTriples(terms: ParseResults) -> List[Any]:
                     last_subject, last_predicate = t[0], None
                     res.append(t[0])
             elif isinstance(t, ParseResults):
-                res += t.asList()
+                res += t.as_list()
             elif t != ".":
                 res.append(t)
                 if (len(res) % 3) == 1:
@@ -126,8 +125,8 @@ def expandBNodeTriples(terms: ParseResults) -> List[Any]:
         if DEBUG:
             print("Bnode terms", terms)
             print("1", terms[0])
-            print("2", [rdflib.BNode()] + terms.asList()[0])
-        return [expandTriples([rdflib.BNode()] + terms.asList()[0])]
+            print("2", [rdflib.BNode()] + terms.as_list()[0])
+        return [expandTriples([rdflib.BNode()] + terms.as_list()[0])]
     except Exception as e:
         if DEBUG:
             print(">>>>>>>>", e)
@@ -170,7 +169,7 @@ IRIREF = Combine(
     + Regex(r'[^<>"{}|^`\\%s]*' % "".join("\\x%02X" % i for i in range(33)))
     + Suppress(">")
 )
-IRIREF.setParseAction(lambda x: rdflib.URIRef(x[0]))
+IRIREF.set_parse_action(lambda x: rdflib.URIRef(x[0]))
 
 # [164] P_CHARS_BASE ::= [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
 
@@ -209,13 +208,13 @@ PN_PREFIX = Regex(
 )
 
 # [140] PNAME_NS ::= PN_PREFIX? ':'
-PNAME_NS = Optional(Param("prefix", PN_PREFIX)) + Suppress(":").leaveWhitespace()
+PNAME_NS = Optional(Param("prefix", PN_PREFIX)) + Suppress(":").leave_whitespace()
 
 # [173] PN_LOCAL_ESC ::= '\' ( '_' | '~' | '.' | '-' | '!' | '$' | '&' | "'" | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%' )
 
 PN_LOCAL_ESC_re = "\\\\[_~\\.\\-!$&\"'()*+,;=/?#@%]"
 # PN_LOCAL_ESC = Regex(PN_LOCAL_ESC_re) # regex'd
-# PN_LOCAL_ESC.setParseAction(lambda x: x[0][1:])
+# PN_LOCAL_ESC.set_parse_action(lambda x: x[0][1:])
 
 # [172] HEX ::= [0-9] | [A-F] | [a-f]
 # HEX = Regex('[0-9A-Fa-f]') # not needed
@@ -223,7 +222,7 @@ PN_LOCAL_ESC_re = "\\\\[_~\\.\\-!$&\"'()*+,;=/?#@%]"
 # [171] PERCENT ::= '%' HEX HEX
 PERCENT_re = "%[0-9a-fA-F]{2}"
 # PERCENT = Regex(PERCENT_re) # regex'd
-# PERCENT.setParseAction(lambda x: chr(int(x[0][1:], 16)))
+# PERCENT.set_parse_action(lambda x: chr(int(x[0][1:], 16)))
 
 # [170] PLX ::= PERCENT | PN_LOCAL_ESC
 PLX_re = "(%s|%s)" % (PN_LOCAL_ESC_re, PERCENT_re)
@@ -242,14 +241,14 @@ PN_LOCAL = Regex(
 
 
 # [141] PNAME_LN ::= PNAME_NS PN_LOCAL
-PNAME_LN = PNAME_NS + Param("localname", PN_LOCAL.leaveWhitespace())
+PNAME_LN = PNAME_NS + Param("localname", PN_LOCAL.leave_whitespace())
 
 # [142] BLANK_NODE_LABEL ::= '_:' ( PN_CHARS_U | [0-9] ) ((PN_CHARS|'.')* PN_CHARS)?
 BLANK_NODE_LABEL = Regex(
     "_:[0-9%s](?:[\\.%s]*[%s])?" % (PN_CHARS_U_re, PN_CHARS_re, PN_CHARS_re),
     flags=re.U,
 )
-BLANK_NODE_LABEL.setParseAction(lambda x: rdflib.BNode(x[0][2:]))
+BLANK_NODE_LABEL.set_parse_action(lambda x: rdflib.BNode(x[0][2:]))
 
 
 # [166] VARNAME ::= ( PN_CHARS_U | [0-9] ) ( PN_CHARS_U | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] )*
@@ -269,46 +268,46 @@ LANGTAG = Combine(Suppress("@") + Regex("[a-zA-Z]+(?:-[a-zA-Z0-9]+)*"))
 
 # [146] INTEGER ::= [0-9]+
 INTEGER = Regex(r"[0-9]+")
-# INTEGER.setResultsName('integer')
-INTEGER.setParseAction(lambda x: rdflib.Literal(x[0], datatype=rdflib.XSD.integer))
+# INTEGER.set_results_name('integer')
+INTEGER.set_parse_action(lambda x: rdflib.Literal(x[0], datatype=rdflib.XSD.integer))
 
 # [155] EXPONENT ::= [eE] [+-]? [0-9]+
 EXPONENT_re = "[eE][+-]?[0-9]+"
 
 # [147] DECIMAL ::= [0-9]* '.' [0-9]+
 DECIMAL = Regex(r"[0-9]*\.[0-9]+")  # (?![eE])
-# DECIMAL.setResultsName('decimal')
-DECIMAL.setParseAction(lambda x: rdflib.Literal(x[0], datatype=rdflib.XSD.decimal))
+# DECIMAL.set_results_name('decimal')
+DECIMAL.set_parse_action(lambda x: rdflib.Literal(x[0], datatype=rdflib.XSD.decimal))
 
 # [148] DOUBLE ::= [0-9]+ '.' [0-9]* EXPONENT | '.' ([0-9])+ EXPONENT | ([0-9])+ EXPONENT
 DOUBLE = Regex(r"[0-9]+\.[0-9]*%(e)s|\.([0-9])+%(e)s|[0-9]+%(e)s" % {"e": EXPONENT_re})
-# DOUBLE.setResultsName('double')
-DOUBLE.setParseAction(lambda x: rdflib.Literal(x[0], datatype=rdflib.XSD.double))
+# DOUBLE.set_results_name('double')
+DOUBLE.set_parse_action(lambda x: rdflib.Literal(x[0], datatype=rdflib.XSD.double))
 
 
 # [149] INTEGER_POSITIVE ::= '+' INTEGER
-INTEGER_POSITIVE = Suppress("+") + INTEGER.copy().leaveWhitespace()
-INTEGER_POSITIVE.setParseAction(
+INTEGER_POSITIVE = Suppress("+") + INTEGER.copy().leave_whitespace()
+INTEGER_POSITIVE.set_parse_action(
     lambda x: rdflib.Literal("+" + x[0], datatype=rdflib.XSD.integer)
 )
 
 # [150] DECIMAL_POSITIVE ::= '+' DECIMAL
-DECIMAL_POSITIVE = Suppress("+") + DECIMAL.copy().leaveWhitespace()
+DECIMAL_POSITIVE = Suppress("+") + DECIMAL.copy().leave_whitespace()
 
 # [151] DOUBLE_POSITIVE ::= '+' DOUBLE
-DOUBLE_POSITIVE = Suppress("+") + DOUBLE.copy().leaveWhitespace()
+DOUBLE_POSITIVE = Suppress("+") + DOUBLE.copy().leave_whitespace()
 
 # [152] INTEGER_NEGATIVE ::= '-' INTEGER
-INTEGER_NEGATIVE = Suppress("-") + INTEGER.copy().leaveWhitespace()
-INTEGER_NEGATIVE.setParseAction(lambda x: neg(x[0]))
+INTEGER_NEGATIVE = Suppress("-") + INTEGER.copy().leave_whitespace()
+INTEGER_NEGATIVE.set_parse_action(lambda x: neg(x[0]))
 
 # [153] DECIMAL_NEGATIVE ::= '-' DECIMAL
-DECIMAL_NEGATIVE = Suppress("-") + DECIMAL.copy().leaveWhitespace()
-DECIMAL_NEGATIVE.setParseAction(lambda x: neg(x[0]))
+DECIMAL_NEGATIVE = Suppress("-") + DECIMAL.copy().leave_whitespace()
+DECIMAL_NEGATIVE.set_parse_action(lambda x: neg(x[0]))
 
 # [154] DOUBLE_NEGATIVE ::= '-' DOUBLE
-DOUBLE_NEGATIVE = Suppress("-") + DOUBLE.copy().leaveWhitespace()
-DOUBLE_NEGATIVE.setParseAction(lambda x: neg(x[0]))
+DOUBLE_NEGATIVE = Suppress("-") + DOUBLE.copy().leave_whitespace()
+DOUBLE_NEGATIVE.set_parse_action(lambda x: neg(x[0]))
 
 # [160] ECHAR ::= '\' [tbnrf\"']
 # ECHAR = Regex('\\\\[tbnrf"\']')
@@ -318,7 +317,7 @@ DOUBLE_NEGATIVE.setParseAction(lambda x: neg(x[0]))
 # STRING_LITERAL_LONG1 = Literal("'''") + ( Optional( Literal("'") | "''"
 # ) + ZeroOrMore( ~ Literal("'\\") | ECHAR ) ) + "'''"
 STRING_LITERAL_LONG1 = Regex("'''((?:'|'')?(?:[^'\\\\]|\\\\['ntbrf\\\\]))*'''")
-STRING_LITERAL_LONG1.setParseAction(
+STRING_LITERAL_LONG1.set_parse_action(
     lambda x: rdflib.Literal(decodeUnicodeEscape(x[0][3:-3]))
 )
 
@@ -326,7 +325,7 @@ STRING_LITERAL_LONG1.setParseAction(
 # STRING_LITERAL_LONG2 = Literal('"""') + ( Optional( Literal('"') | '""'
 # ) + ZeroOrMore( ~ Literal('"\\') | ECHAR ) ) +  '"""'
 STRING_LITERAL_LONG2 = Regex('"""(?:(?:"|"")?(?:[^"\\\\]|\\\\["ntbrf\\\\]))*"""')
-STRING_LITERAL_LONG2.setParseAction(
+STRING_LITERAL_LONG2.set_parse_action(
     lambda x: rdflib.Literal(decodeUnicodeEscape(x[0][3:-3]))
 )
 
@@ -335,7 +334,7 @@ STRING_LITERAL_LONG2.setParseAction(
 # Regex(u'[^\u0027\u005C\u000A\u000D]',flags=re.U) | ECHAR ) + "'"
 
 STRING_LITERAL1 = Regex("'(?:[^'\\n\\r\\\\]|\\\\['ntbrf\\\\])*'(?!')", flags=re.U)
-STRING_LITERAL1.setParseAction(
+STRING_LITERAL1.set_parse_action(
     lambda x: rdflib.Literal(decodeUnicodeEscape(x[0][1:-1]))
 )
 
@@ -344,24 +343,24 @@ STRING_LITERAL1.setParseAction(
 # Regex(u'[^\u0022\u005C\u000A\u000D]',flags=re.U) | ECHAR ) + '"'
 
 STRING_LITERAL2 = Regex('"(?:[^"\\n\\r\\\\]|\\\\["ntbrf\\\\])*"(?!")', flags=re.U)
-STRING_LITERAL2.setParseAction(
+STRING_LITERAL2.set_parse_action(
     lambda x: rdflib.Literal(decodeUnicodeEscape(x[0][1:-1]))
 )
 
 # [161] NIL ::= '(' WS* ')'
 NIL = Literal("(") + ")"
-NIL.setParseAction(lambda x: rdflib.RDF.nil)
+NIL.set_parse_action(lambda x: rdflib.RDF.nil)
 
 # [162] WS ::= #x20 | #x9 | #xD | #xA
 # Not needed?
 # WS = #x20 | #x9 | #xD | #xA
 # [163] ANON ::= '[' WS* ']'
 ANON = Literal("[") + "]"
-ANON.setParseAction(lambda x: rdflib.BNode())
+ANON.set_parse_action(lambda x: rdflib.BNode())
 
 # A = CaseSensitiveKeyword('a')
 A = Literal("a")
-A.setParseAction(lambda x: rdflib.RDF.type)
+A.set_parse_action(lambda x: rdflib.RDF.type)
 
 
 # ------ NON-TERMINALS --------------
@@ -377,7 +376,7 @@ Prologue = Group(ZeroOrMore(BaseDecl | PrefixDecl))
 
 # [108] Var ::= VAR1 | VAR2
 Var = VAR1 | VAR2
-Var.setParseAction(lambda x: rdflib.term.Variable(x[0]))
+Var.set_parse_action(lambda x: rdflib.term.Variable(x[0]))
 
 # [137] PrefixedName ::= PNAME_LN | PNAME_NS
 PrefixedName = Comp("pname", PNAME_LN | PNAME_NS)
@@ -394,8 +393,8 @@ RDFLiteral = Comp(
     "literal",
     Param("string", String)
     + Optional(
-        Param("lang", LANGTAG.leaveWhitespace())
-        | Literal("^^").leaveWhitespace() + Param("datatype", iri).leaveWhitespace()
+        Param("lang", LANGTAG.leave_whitespace())
+        | Literal("^^").leave_whitespace() + Param("datatype", iri).leave_whitespace()
     ),
 )
 
@@ -414,9 +413,9 @@ NumericLiteral = (
 )
 
 # [134] BooleanLiteral ::= 'true' | 'false'
-BooleanLiteral = Keyword("true").setParseAction(lambda: rdflib.Literal(True)) | Keyword(
-    "false"
-).setParseAction(lambda: rdflib.Literal(False))
+BooleanLiteral = Keyword("true").set_parse_action(
+    lambda: rdflib.Literal(True)
+) | Keyword("false").set_parse_action(lambda: rdflib.Literal(False))
 
 # [138] BlankNode ::= BLANK_NODE_LABEL | ANON
 BlankNode = BLANK_NODE_LABEL | ANON
@@ -502,7 +501,7 @@ PathPrimary = (
 # [91] PathElt ::= PathPrimary Optional(PathMod)
 PathElt = Comp(
     "PathElt",
-    Param("part", PathPrimary) + Optional(Param("mod", PathMod.leaveWhitespace())),
+    Param("part", PathPrimary) + Optional(Param("mod", PathMod.leave_whitespace())),
 )
 
 # [92] PathEltOrInverse ::= PathElt | '^' PathElt
@@ -542,11 +541,11 @@ GroupGraphPattern = Forward()
 
 # [102] Collection ::= '(' OneOrMore(GraphNode) ')'
 Collection = Suppress("(") + OneOrMore(GraphNode) + Suppress(")")
-Collection.setParseAction(expandCollection)
+Collection.set_parse_action(expandCollection)
 
 # [103] CollectionPath ::= '(' OneOrMore(GraphNodePath) ')'
 CollectionPath = Suppress("(") + OneOrMore(GraphNodePath) + Suppress(")")
-CollectionPath.setParseAction(expandCollection)
+CollectionPath.set_parse_action(expandCollection)
 
 # [80] Object ::= GraphNode
 Object = GraphNode
@@ -573,13 +572,13 @@ PropertyList = Optional(PropertyListNotEmpty)
 
 # [99] BlankNodePropertyList ::= '[' PropertyListNotEmpty ']'
 BlankNodePropertyList = Group(Suppress("[") + PropertyListNotEmpty + Suppress("]"))
-BlankNodePropertyList.setParseAction(expandBNodeTriples)
+BlankNodePropertyList.set_parse_action(expandBNodeTriples)
 
 # [101] BlankNodePropertyListPath ::= '[' PropertyListPathNotEmpty ']'
 BlankNodePropertyListPath = Group(
     Suppress("[") + PropertyListPathNotEmpty + Suppress("]")
 )
-BlankNodePropertyListPath.setParseAction(expandBNodeTriples)
+BlankNodePropertyListPath.set_parse_action(expandBNodeTriples)
 
 # [98] TriplesNode ::= Collection | BlankNodePropertyList
 TriplesNode <<= Collection | BlankNodePropertyList
@@ -589,7 +588,7 @@ TriplesNodePath <<= CollectionPath | BlankNodePropertyListPath
 
 # [75] TriplesSameSubject ::= VarOrTerm PropertyListNotEmpty | TriplesNode PropertyList
 TriplesSameSubject = VarOrTerm + PropertyListNotEmpty | TriplesNode + PropertyList
-TriplesSameSubject.setParseAction(expandTriples)
+TriplesSameSubject.set_parse_action(expandTriples)
 
 # [52] TriplesTemplate ::= TriplesSameSubject ( '.' TriplesTemplate? )?
 # NOTE: pyparsing.py handling of recursive rules is limited by python's recursion
@@ -629,7 +628,7 @@ QuadData = "{" + Param("quads", Quads) + "}"
 TriplesSameSubjectPath = (
     VarOrTerm + PropertyListPathNotEmpty | TriplesNodePath + PropertyListPath
 )
-TriplesSameSubjectPath.setParseAction(expandTriples)
+TriplesSameSubjectPath.set_parse_action(expandTriples)
 
 # [55] TriplesBlock ::= TriplesSameSubjectPath ( '.' Optional(TriplesBlock) )?
 TriplesBlock = Forward()
@@ -654,7 +653,7 @@ GroupOrUnionGraphPattern = Comp(
 Expression = Forward()
 
 # [72] ExpressionList ::= NIL | '(' Expression ( ',' Expression )* ')'
-ExpressionList = NIL | Group(Suppress("(") + delimitedList(Expression) + Suppress(")"))
+ExpressionList = NIL | Group(Suppress("(") + DelimitedList(Expression) + Suppress(")"))
 
 # [122] RegexExpression ::= 'REGEX' '(' Expression ',' Expression ( ',' Expression )? ')'
 RegexExpression = Comp(
@@ -1015,7 +1014,7 @@ ArgList = (
     NIL
     | "("
     + Param("distinct", _Distinct)
-    + delimitedList(ParamList("expr", Expression))
+    + DelimitedList(ParamList("expr", Expression))
     + ")"
 )
 
@@ -1101,7 +1100,11 @@ RelationalExpression = Comp(
         | Param("op", Keyword("IN")) + Param("other", ExpressionList)
         | Param(
             "op",
-            Combine(Keyword("NOT") + Keyword("IN"), adjacent=False, joinString=" "),
+            Combine(
+                Keyword("NOT") + Keyword("IN"),
+                adjacent=False,
+                **combine_join_kwargs(" "),
+            ),
         )
         + Param("other", ExpressionList)
     ),
@@ -1519,8 +1522,8 @@ UpdateUnit = Comp("Update", Update)
 # [1] QueryUnit ::= Query
 QueryUnit = Query
 
-QueryUnit.ignore("#" + restOfLine)
-UpdateUnit.ignore("#" + restOfLine)
+QueryUnit.ignore("#" + rest_of_line)
+UpdateUnit.ignore("#" + rest_of_line)
 
 
 expandUnicodeEscapes_re: re.Pattern = re.compile(
@@ -1550,7 +1553,7 @@ def parseQuery(q: Union[str, bytes, TextIO, BinaryIO]) -> ParseResults:
         q = q.decode("utf-8")
 
     q = expandUnicodeEscapes(q)
-    return Query.parseString(q, parseAll=True)
+    return Query.parse_string(q, parse_all=True)
 
 
 def parseUpdate(q: Union[str, bytes, TextIO, BinaryIO]) -> CompValue:
@@ -1561,4 +1564,4 @@ def parseUpdate(q: Union[str, bytes, TextIO, BinaryIO]) -> CompValue:
         q = q.decode("utf-8")
 
     q = expandUnicodeEscapes(q)
-    return UpdateUnit.parseString(q, parseAll=True)[0]
+    return UpdateUnit.parse_string(q, parse_all=True)[0]
diff --git a/rdflib/plugins/sparql/parserutils.py b/rdflib/plugins/sparql/parserutils.py
index 43af286c..9b6be93a 100644
--- a/rdflib/plugins/sparql/parserutils.py
+++ b/rdflib/plugins/sparql/parserutils.py
@@ -39,10 +39,12 @@ from typing import (
     Union,
 )
 
-from pyparsing import ParserElement, ParseResults, TokenConverter, originalTextFor
+from pyparsing import ParserElement, ParseResults, TokenConverter
 
 from rdflib.term import BNode, Identifier, Variable
 
+from .pyparsing_compat import original_text_for
+
 if TYPE_CHECKING:
     from rdflib.plugins.sparql.sparql import FrozenBindings
 
@@ -126,8 +128,8 @@ class Param(TokenConverter):
     def __init__(self, name: str, expr, isList: bool = False):
         self.isList = isList
         TokenConverter.__init__(self, expr)
-        self.setName(name)
-        self.addParseAction(self.postParse2)
+        self.set_name(name)
+        self.add_parse_action(self.postParse2)
 
     def postParse2(self, tokenList: Union[List[Any], ParseResults]) -> ParamValue:
         return ParamValue(self.name, tokenList, self.isList)
@@ -236,7 +238,7 @@ class Comp(TokenConverter):
     def __init__(self, name: str, expr: ParserElement):
         self.expr = expr
         TokenConverter.__init__(self, expr)
-        self.setName(name)
+        self.set_name(name)
         self.evalfn: Optional[Callable[[Any, Any], Any]] = None
 
     def postParse(
@@ -252,8 +254,8 @@ class Comp(TokenConverter):
                 # Then this must be a service graph pattern and have
                 # already matched.
                 # lets assume there is one, for now, then test for two later.
-                sgp = originalTextFor(self.expr)
-                service_string = sgp.searchString(instring)[0][0]
+                sgp = original_text_for(self.expr)
+                service_string = sgp.search_string(instring)[0][0]
                 res["service_string"] = service_string
 
         for t in tokenList:
@@ -276,7 +278,7 @@ class Comp(TokenConverter):
 
 def prettify_parsetree(t: ParseResults, indent: str = "", depth: int = 0) -> str:
     out: List[str] = []
-    for e in t.asList():
+    for e in t.as_list():
         out.append(_prettify_sub_parsetree(e, indent, depth + 1))
     for k, v in sorted(t.items()):
         out.append("%s%s- %s:\n" % (indent, "  " * depth, k))
diff --git a/rdflib/plugins/sparql/pyparsing_compat.py b/rdflib/plugins/sparql/pyparsing_compat.py
new file mode 100644
index 00000000..91a0c737
--- /dev/null
+++ b/rdflib/plugins/sparql/pyparsing_compat.py
@@ -0,0 +1,100 @@
+"""
+Compatibility helpers for supporting pyparsing v2 and v3 APIs.
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Dict, Type, cast
+
+import pyparsing
+
+ParseResults = pyparsing.ParseResults
+ParserElement = pyparsing.ParserElement
+
+
+_RAW_VERSION = getattr(pyparsing, "__version__", "0")
+try:
+    PYPARSING_MAJOR_VERSION = int(_RAW_VERSION.split(".", 1)[0])
+except (TypeError, ValueError):
+    PYPARSING_MAJOR_VERSION = 0
+
+PYPARSING_V3 = PYPARSING_MAJOR_VERSION >= 3
+
+_ParserFactory = Callable[..., ParserElement]
+_ParserTransform = Callable[..., ParserElement]
+
+DelimitedList: _ParserFactory
+original_text_for: _ParserTransform
+rest_of_line: ParserElement
+
+if PYPARSING_V3:
+    DelimitedList = pyparsing.DelimitedList
+    original_text_for = pyparsing.original_text_for
+    rest_of_line = pyparsing.rest_of_line
+else:
+    DelimitedList = pyparsing.delimitedList
+    original_text_for = pyparsing.originalTextFor
+    rest_of_line = pyparsing.restOfLine
+
+
+def _alias_instance_method(klass: Type[object], new_name: str, old_name: str) -> None:
+    if hasattr(klass, new_name) or not hasattr(klass, old_name):
+        return
+
+    def _method(self: object, *args: object, **kwargs: object) -> object:
+        # Resolve old_name on self so subclass overrides are preserved.
+        method = cast(Callable[..., object], getattr(self, old_name))
+        return method(*args, **kwargs)
+
+    setattr(klass, new_name, _method)
+
+
+def _alias_static_method(klass: Type[object], new_name: str, old_name: str) -> None:
+    if hasattr(klass, new_name) or not hasattr(klass, old_name):
+        return
+
+    old_method = cast(Callable[..., object], getattr(klass, old_name))
+
+    def _method(*args: object, **kwargs: object) -> object:
+        return old_method(*args, **kwargs)
+
+    setattr(klass, new_name, staticmethod(_method))
+
+
+_alias_instance_method(ParserElement, "set_parse_action", "setParseAction")
+_alias_instance_method(ParserElement, "add_parse_action", "addParseAction")
+_alias_instance_method(ParserElement, "leave_whitespace", "leaveWhitespace")
+_alias_instance_method(ParserElement, "set_name", "setName")
+_alias_instance_method(ParserElement, "set_results_name", "setResultsName")
+_alias_instance_method(ParserElement, "parse_with_tabs", "parseWithTabs")
+_alias_instance_method(ParserElement, "search_string", "searchString")
+_alias_static_method(
+    ParserElement,
+    "set_default_whitespace_chars",
+    "setDefaultWhitespaceChars",
+)
+
+if not hasattr(ParserElement, "parse_string"):
+
+    def _parse_string(
+        self: ParserElement,
+        instring: str,
+        parse_all: bool = False,
+        *,
+        parseAll: bool = False,
+    ) -> ParseResults:
+        if parseAll:
+            parse_all = parseAll
+        parser = cast(Callable[..., ParseResults], getattr(self, "parseString"))
+        return parser(instring, parseAll=parse_all)
+
+    setattr(ParserElement, "parse_string", _parse_string)
+
+
+_alias_instance_method(ParseResults, "as_list", "asList")
+
+
+def combine_join_kwargs(value: str) -> Dict[str, str]:
+    if PYPARSING_V3:
+        return {"join_string": value}
+    return {"joinString": value}
diff --git a/rdflib/plugins/sparql/results/tsvresults.py b/rdflib/plugins/sparql/results/tsvresults.py
index 14741718..54d8ee16 100644
--- a/rdflib/plugins/sparql/results/tsvresults.py
+++ b/rdflib/plugins/sparql/results/tsvresults.py
@@ -32,10 +32,10 @@ from rdflib.plugins.sparql.parser import (
 )
 from rdflib.plugins.sparql.parserutils import Comp, CompValue, Param
 from rdflib.query import Result, ResultParser
-from rdflib.term import BNode, URIRef
+from rdflib.term import BNode, Identifier, URIRef
 from rdflib.term import Literal as RDFLiteral
 
-ParserElement.setDefaultWhitespaceChars(" \n")
+ParserElement.set_default_whitespace_chars(" \n")
 
 
 String = STRING_LITERAL1 | STRING_LITERAL2
@@ -44,23 +44,24 @@ RDFLITERAL = Comp(
     "literal",
     Param("string", String)
     + Optional(
-        Param("lang", LANGTAG.leaveWhitespace())
-        | Literal("^^").leaveWhitespace() + Param("datatype", IRIREF).leaveWhitespace()
+        Param("lang", LANGTAG.leave_whitespace())
+        | Literal("^^").leave_whitespace()
+        + Param("datatype", IRIREF).leave_whitespace()
     ),
 )
 
 NONE_VALUE = object()
 
 EMPTY = FollowedBy(LineEnd()) | FollowedBy("\t")
-EMPTY.setParseAction(lambda x: NONE_VALUE)
+EMPTY.set_parse_action(lambda x: NONE_VALUE)
 
 TERM = RDFLITERAL | IRIREF | BLANK_NODE_LABEL | NumericLiteral | BooleanLiteral
 
 ROW = (EMPTY | TERM) + ZeroOrMore(Suppress("\t") + (EMPTY | TERM))
-ROW.parseWithTabs()
+ROW.parse_with_tabs()
 
 HEADER = Var + ZeroOrMore(Suppress("\t") + Var)
-HEADER.parseWithTabs()
+HEADER.parse_with_tabs()
 
 
 class TSVResultParser(ResultParser):
@@ -77,7 +78,7 @@ class TSVResultParser(ResultParser):
 
         header = source.readline()
 
-        r.vars = list(HEADER.parseString(header.strip(), parseAll=True))
+        r.vars = list(HEADER.parse_string(header.strip(), parse_all=True))
         r.bindings = []
         while True:
             line = source.readline()
@@ -87,15 +88,21 @@ class TSVResultParser(ResultParser):
             if line == "":
                 continue
 
-            row = ROW.parseString(line, parseAll=True)
-            # type error: Generator has incompatible item type "object"; expected "Identifier"
-            r.bindings.append(dict(zip(r.vars, (self.convertTerm(x) for x in row))))  # type: ignore[misc]
-
+            row = ROW.parse_string(line, parse_all=True)
+            this_row_dict = {}
+            for var, val_read in zip(r.vars, row):
+                val = self.convertTerm(val_read)
+                if val is None:
+                    # Skip unbound vars
+                    continue
+                this_row_dict[var] = val
+            # Preserve solution row cardinality, including fully-unbound rows.
+            r.bindings.append(this_row_dict)
         return r
 
     def convertTerm(
         self, t: Union[object, RDFLiteral, BNode, CompValue, URIRef]
-    ) -> typing.Optional[Union[object, BNode, URIRef, RDFLiteral]]:
+    ) -> typing.Optional[Identifier]:
         if t is NONE_VALUE:
             return None
         if isinstance(t, CompValue):
@@ -103,5 +110,7 @@ class TSVResultParser(ResultParser):
                 return RDFLiteral(t.string, lang=t.lang, datatype=t.datatype)
             else:
                 raise Exception("I dont know how to handle this: %s" % (t,))
-        else:
+        elif isinstance(t, (RDFLiteral, BNode, URIRef)):
             return t
+        else:
+            raise ValueError(f"Unexpected type {type(t)} found in TSV result")