Benjamin-eecs's picture
release v1: 65 held-out tasks, 78 bootstrap records, r2e_local adapter, manifest ae94c40b (part 4)
622387b verified
Raw History Blame Contribute Delete
23.9 kB
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")