Skip to content

parser

SPARQL 1.1 Parser

based on pyparsing

Functions:

Attributes:

A module-attribute

A = Literal('a')

ANON module-attribute

ANON = Literal('[') + ']'

Add module-attribute

Add = Comp('Add', CaselessKeyword('ADD') + _Silent + GraphOrDefault + CaselessKeyword('TO') + GraphOrDefault)

AdditiveExpression module-attribute

AdditiveExpression = setEvalFn(AdditiveExpression)

Aggregate module-attribute

Aggregate = Comp('Aggregate_Count', CaselessKeyword('COUNT') + '(' + Param('distinct', _Distinct) + Param('vars', '*' | Expression) + ')') | Comp('Aggregate_Sum', CaselessKeyword('SUM') + _AggregateParams) | Comp('Aggregate_Min', CaselessKeyword('MIN') + _AggregateParams) | Comp('Aggregate_Max', CaselessKeyword('MAX') + _AggregateParams) | Comp('Aggregate_Avg', CaselessKeyword('AVG') + _AggregateParams) | Comp('Aggregate_Sample', CaselessKeyword('SAMPLE') + _AggregateParams) | Comp('Aggregate_GroupConcat', CaselessKeyword('GROUP_CONCAT') + '(' + Param('distinct', _Distinct) + Param('vars', Expression) + Optional(';' + CaselessKeyword('SEPARATOR') + '=' + Param('separator', String)) + ')')

ArgList module-attribute

ArgList = NIL | '(' + Param('distinct', _Distinct) + delimitedList(ParamList('expr', Expression)) + ')'

AskQuery module-attribute

AskQuery = Comp('AskQuery', CaselessKeyword('ASK') + ZeroOrMore(ParamList('datasetClause', DatasetClause)) + WhereClause + SolutionModifier + ValuesClause)

BLANK_NODE_LABEL module-attribute

BLANK_NODE_LABEL = Regex('_:[0-9%s](?:[\\.%s]*[%s])?' % (PN_CHARS_U_re, PN_CHARS_re, PN_CHARS_re), flags=U)

BaseDecl module-attribute

BaseDecl = Comp('Base', CaselessKeyword('BASE') + Param('iri', IRIREF))

Bind module-attribute

Bind = Comp('Bind', CaselessKeyword('BIND') + '(' + Param('expr', Expression) + CaselessKeyword('AS') + Param('var', Var) + ')')

BlankNode module-attribute

BlankNode = BLANK_NODE_LABEL | ANON

BlankNodePropertyList module-attribute

BlankNodePropertyList = Group(Suppress('[') + PropertyListNotEmpty + Suppress(']'))

BlankNodePropertyListPath module-attribute

BlankNodePropertyListPath = Group(Suppress('[') + PropertyListPathNotEmpty + Suppress(']'))

BooleanLiteral module-attribute

BooleanLiteral = setParseAction(lambda: Literal(True)) | setParseAction(lambda: Literal(False))

BrackettedExpression module-attribute

BrackettedExpression = Suppress('(') + Expression + Suppress(')')

BuiltInCall module-attribute

BuiltInCall = Aggregate | setEvalFn(Builtin_STR) | setEvalFn(Builtin_LANG) | setEvalFn(Builtin_LANGMATCHES) | setEvalFn(Builtin_DATATYPE) | setEvalFn(Builtin_BOUND) | setEvalFn(Builtin_IRI) | setEvalFn(Builtin_IRI) | setEvalFn(Builtin_BNODE) | setEvalFn(Builtin_RAND) | setEvalFn(Builtin_ABS) | setEvalFn(Builtin_CEIL) | setEvalFn(Builtin_FLOOR) | setEvalFn(Builtin_ROUND) | setEvalFn(Builtin_CONCAT) | SubstringExpression | setEvalFn(Builtin_STRLEN) | StrReplaceExpression | setEvalFn(Builtin_UCASE) | setEvalFn(Builtin_LCASE) | setEvalFn(Builtin_ENCODE_FOR_URI) | setEvalFn(Builtin_CONTAINS) | setEvalFn(Builtin_STRSTARTS) | setEvalFn(Builtin_STRENDS) | setEvalFn(Builtin_STRBEFORE) | setEvalFn(Builtin_STRAFTER) | setEvalFn(Builtin_YEAR) | setEvalFn(Builtin_MONTH) | setEvalFn(Builtin_DAY) | setEvalFn(Builtin_HOURS) | setEvalFn(Builtin_MINUTES) | setEvalFn(Builtin_SECONDS) | setEvalFn(Builtin_TIMEZONE) | setEvalFn(Builtin_TZ) | setEvalFn(Builtin_NOW) | setEvalFn(Builtin_UUID) | setEvalFn(Builtin_STRUUID) | setEvalFn(Builtin_MD5) | setEvalFn(Builtin_SHA1) | setEvalFn(Builtin_SHA256) | setEvalFn(Builtin_SHA384) | setEvalFn(Builtin_SHA512) | setEvalFn(Builtin_COALESCE) | setEvalFn(Builtin_IF) | setEvalFn(Builtin_STRLANG) | setEvalFn(Builtin_STRDT) | setEvalFn(Builtin_sameTerm) | setEvalFn(Builtin_isIRI) | setEvalFn(Builtin_isIRI) | setEvalFn(Builtin_isBLANK) | setEvalFn(Builtin_isLITERAL) | setEvalFn(Builtin_isNUMERIC) | RegexExpression | ExistsFunc | NotExistsFunc

Clear module-attribute

Clear = Comp('Clear', CaselessKeyword('CLEAR') + _Silent + GraphRefAll)

Collection module-attribute

Collection = Suppress('(') + OneOrMore(GraphNode) + Suppress(')')

CollectionPath module-attribute

CollectionPath = Suppress('(') + OneOrMore(GraphNodePath) + Suppress(')')

ConditionalAndExpression module-attribute

ConditionalAndExpression = setEvalFn(ConditionalAndExpression)

ConditionalOrExpression module-attribute

ConditionalOrExpression = setEvalFn(ConditionalOrExpression)

Constraint module-attribute

ConstructQuery module-attribute

ConstructQuery = Comp('ConstructQuery', CaselessKeyword('CONSTRUCT') + (ConstructTemplate + ZeroOrMore(ParamList('datasetClause', DatasetClause)) + WhereClause + SolutionModifier + ValuesClause | ZeroOrMore(ParamList('datasetClause', DatasetClause)) + CaselessKeyword('WHERE') + '{' + Optional(Param('where', Comp('FakeGroupGraphPatten', ParamList('part', Comp('TriplesBlock', TriplesTemplate))))) + '}' + SolutionModifier + ValuesClause))

ConstructTemplate module-attribute

ConstructTemplate = Suppress('{') + Optional(ConstructTriples) + Suppress('}')

ConstructTriples module-attribute

ConstructTriples = Forward()

Copy module-attribute

Copy = Comp('Copy', CaselessKeyword('COPY') + _Silent + GraphOrDefault + CaselessKeyword('TO') + GraphOrDefault)

Create module-attribute

Create = Comp('Create', CaselessKeyword('CREATE') + _Silent + GraphRef)

DEBUG module-attribute

DEBUG = False

DECIMAL module-attribute

DECIMAL = Regex('[0-9]*\\.[0-9]+')

DECIMAL_NEGATIVE module-attribute

DECIMAL_NEGATIVE = Suppress('-') + leaveWhitespace()

DECIMAL_POSITIVE module-attribute

DECIMAL_POSITIVE = Suppress('+') + leaveWhitespace()

DOUBLE module-attribute

DOUBLE = Regex('[0-9]+\\.[0-9]*%(e)s|\\.([0-9])+%(e)s|[0-9]+%(e)s' % {'e': EXPONENT_re})

DOUBLE_NEGATIVE module-attribute

DOUBLE_NEGATIVE = Suppress('-') + leaveWhitespace()

DOUBLE_POSITIVE module-attribute

DOUBLE_POSITIVE = Suppress('+') + leaveWhitespace()

DataBlock module-attribute

DataBlockValue module-attribute

DataBlockValue = iri | RDFLiteral | NumericLiteral | BooleanLiteral | CaselessKeyword('UNDEF')

DatasetClause module-attribute

DatasetClause = Comp('DatasetClause', CaselessKeyword('FROM') + (Param('default', DefaultGraphClause) | NamedGraphClause))

DefaultGraphClause module-attribute

DefaultGraphClause = SourceSelector

DeleteClause module-attribute

DeleteClause = Comp('DeleteClause', CaselessKeyword('DELETE') + QuadPattern)

DeleteData module-attribute

DeleteData = Comp('DeleteData', CaselessKeyword('DELETE') + CaselessKeyword('DATA') + QuadData)

DeleteWhere module-attribute

DeleteWhere = Comp('DeleteWhere', CaselessKeyword('DELETE') + CaselessKeyword('WHERE') + QuadPattern)

DescribeQuery module-attribute

DescribeQuery = Comp('DescribeQuery', CaselessKeyword('DESCRIBE') + (OneOrMore(ParamList('var', VarOrIri)) | '*') + ZeroOrMore(ParamList('datasetClause', DatasetClause)) + Optional(WhereClause) + SolutionModifier + ValuesClause)

Drop module-attribute

Drop = Comp('Drop', CaselessKeyword('DROP') + _Silent + GraphRefAll)

EXPONENT_re module-attribute

EXPONENT_re = '[eE][+-]?[0-9]+'

ExistsFunc module-attribute

ExistsFunc = setEvalFn(Builtin_EXISTS)

Expression module-attribute

Expression = Forward()

ExpressionList module-attribute

ExpressionList = NIL | Group(Suppress('(') + delimitedList(Expression) + Suppress(')'))

Filter module-attribute

Filter = Comp('Filter', CaselessKeyword('FILTER') + Param('expr', Constraint))

FunctionCall module-attribute

FunctionCall = setEvalFn(Function)

GraphGraphPattern module-attribute

GraphGraphPattern = Comp('GraphGraphPattern', CaselessKeyword('GRAPH') + Param('term', VarOrIri) + Param('graph', GroupGraphPattern))

GraphNode module-attribute

GraphNode = VarOrTerm | TriplesNode

GraphNodePath module-attribute

GraphNodePath = VarOrTerm | TriplesNodePath

GraphOrDefault module-attribute

GraphOrDefault = ParamList('graph', CaselessKeyword('DEFAULT')) | Optional(CaselessKeyword('GRAPH')) + ParamList('graph', iri)

GraphPatternNotTriples module-attribute

GraphRef module-attribute

GraphRef = CaselessKeyword('GRAPH') + Param('graphiri', iri)

GraphRefAll module-attribute

GraphRefAll = GraphRef | Param('graphiri', CaselessKeyword('DEFAULT')) | Param('graphiri', CaselessKeyword('NAMED')) | Param('graphiri', CaselessKeyword('ALL'))

GraphTerm module-attribute

GroupClause module-attribute

GroupClause = Comp('GroupClause', CaselessKeyword('GROUP') + CaselessKeyword('BY') + OneOrMore(ParamList('condition', GroupCondition)))

GroupCondition module-attribute

GroupCondition = BuiltInCall | FunctionCall | Comp('GroupAs', '(' + Param('expr', Expression) + Optional(CaselessKeyword('AS') + Param('var', Var)) + ')') | Var

GroupGraphPattern module-attribute

GroupGraphPattern = Forward()

GroupGraphPatternSub module-attribute

GroupGraphPatternSub = Comp('GroupGraphPatternSub', Optional(ParamList('part', Comp('TriplesBlock', TriplesBlock))) + ZeroOrMore(ParamList('part', GraphPatternNotTriples) + Optional('.') + Optional(ParamList('part', Comp('TriplesBlock', TriplesBlock)))))

GroupOrUnionGraphPattern module-attribute

GroupOrUnionGraphPattern = Comp('GroupOrUnionGraphPattern', ParamList('graph', GroupGraphPattern) + ZeroOrMore(CaselessKeyword('UNION') + ParamList('graph', GroupGraphPattern)))

HavingClause module-attribute

HavingClause = Comp('HavingClause', CaselessKeyword('HAVING') + OneOrMore(ParamList('condition', HavingCondition)))

HavingCondition module-attribute

HavingCondition = Constraint

INTEGER module-attribute

INTEGER = Regex('[0-9]+')

INTEGER_NEGATIVE module-attribute

INTEGER_NEGATIVE = Suppress('-') + leaveWhitespace()

INTEGER_POSITIVE module-attribute

INTEGER_POSITIVE = Suppress('+') + leaveWhitespace()

IRIREF module-attribute

IRIREF = Combine(Suppress('<') + Regex('[^<>"{}|^`\\\\%s]*' % join(('\\x%02X' % i) for i in (range(33)))) + Suppress('>'))

InlineData module-attribute

InlineData = Comp('InlineData', CaselessKeyword('VALUES') + DataBlock)

InlineDataFull module-attribute

InlineDataFull = (NIL | '(' + ZeroOrMore(ParamList('var', Var)) + ')') + '{' + ZeroOrMore(ParamList('value', Group(Suppress('(') + ZeroOrMore(DataBlockValue) + Suppress(')') | NIL))) + '}'

InlineDataOneVar module-attribute

InlineDataOneVar = ParamList('var', Var) + '{' + ZeroOrMore(ParamList('value', DataBlockValue)) + '}'

InsertClause module-attribute

InsertClause = Comp('InsertClause', CaselessKeyword('INSERT') + QuadPattern)

InsertData module-attribute

InsertData = Comp('InsertData', CaselessKeyword('INSERT') + CaselessKeyword('DATA') + QuadData)

Integer module-attribute

Integer = INTEGER

LANGTAG module-attribute

LANGTAG = Combine(Suppress('@') + Regex('[a-zA-Z]+(?:-[a-zA-Z0-9]+)*'))

LimitClause module-attribute

LimitClause = CaselessKeyword('LIMIT') + Param('limit', INTEGER)

LimitOffsetClauses module-attribute

LimitOffsetClauses = Comp('LimitOffsetClauses', LimitClause + Optional(OffsetClause) | OffsetClause + Optional(LimitClause))

Load module-attribute

Load = Comp('Load', CaselessKeyword('LOAD') + _Silent + Param('iri', iri) + Optional(CaselessKeyword('INTO') + GraphRef))

MinusGraphPattern module-attribute

MinusGraphPattern = Comp('MinusGraphPattern', CaselessKeyword('MINUS') + Param('graph', GroupGraphPattern))

Modify module-attribute

Modify = Comp('Modify', Optional(CaselessKeyword('WITH') + Param('withClause', iri)) + (Param('delete', DeleteClause) + Optional(Param('insert', InsertClause)) | Param('insert', InsertClause)) + ZeroOrMore(ParamList('using', UsingClause)) + CaselessKeyword('WHERE') + Param('where', GroupGraphPattern))

Move module-attribute

Move = Comp('Move', CaselessKeyword('MOVE') + _Silent + GraphOrDefault + CaselessKeyword('TO') + GraphOrDefault)

MultiplicativeExpression module-attribute

MultiplicativeExpression = setEvalFn(MultiplicativeExpression)

NIL module-attribute

NIL = Literal('(') + ')'

NamedGraphClause module-attribute

NamedGraphClause = CaselessKeyword('NAMED') + Param('named', SourceSelector)

NotExistsFunc module-attribute

NotExistsFunc = setEvalFn(Builtin_EXISTS)

NumericExpression module-attribute

NumericExpression = AdditiveExpression

NumericLiteral module-attribute

NumericLiteralNegative module-attribute

NumericLiteralNegative = DOUBLE_NEGATIVE | DECIMAL_NEGATIVE | INTEGER_NEGATIVE

NumericLiteralPositive module-attribute

NumericLiteralPositive = DOUBLE_POSITIVE | DECIMAL_POSITIVE | INTEGER_POSITIVE

NumericLiteralUnsigned module-attribute

NumericLiteralUnsigned = DOUBLE | DECIMAL | INTEGER

Object module-attribute

Object = GraphNode

ObjectList module-attribute

ObjectList = Object + ZeroOrMore(',' + Object)

ObjectListPath module-attribute

ObjectListPath = ObjectPath + ZeroOrMore(',' + ObjectPath)

ObjectPath module-attribute

ObjectPath = GraphNodePath

OffsetClause module-attribute

OffsetClause = CaselessKeyword('OFFSET') + Param('offset', INTEGER)

OptionalGraphPattern module-attribute

OptionalGraphPattern = Comp('OptionalGraphPattern', CaselessKeyword('OPTIONAL') + Param('graph', GroupGraphPattern))

OrderClause module-attribute

OrderClause = Comp('OrderClause', CaselessKeyword('ORDER') + CaselessKeyword('BY') + OneOrMore(ParamList('condition', OrderCondition)))

OrderCondition module-attribute

OrderCondition = Comp('OrderCondition', Param('order', CaselessKeyword('ASC') | CaselessKeyword('DESC')) + Param('expr', BrackettedExpression) | Param('expr', Constraint | Var))

PERCENT_re module-attribute

PERCENT_re = '%[0-9a-fA-F]{2}'

PLX_re module-attribute

PLX_re = '(%s|%s)' % (PN_LOCAL_ESC_re, PERCENT_re)

PNAME_LN module-attribute

PNAME_LN = PNAME_NS + Param('localname', leaveWhitespace())

PNAME_NS module-attribute

PNAME_NS = Optional(Param('prefix', PN_PREFIX)) + leaveWhitespace()

PN_CHARS_BASE_re module-attribute

PN_CHARS_BASE_re = 'A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-\u1fff\u200c-\u200d⁰-\u218fⰀ-\u2fef、-\ud7ff豈-﷏ﷰ-�'

PN_CHARS_U_re module-attribute

PN_CHARS_U_re = '_' + PN_CHARS_BASE_re

PN_CHARS_re module-attribute

PN_CHARS_re = '\\-0-9·̀-ͯ‿-⁀' + PN_CHARS_U_re

PN_LOCAL module-attribute

PN_LOCAL = Regex('([%(PN_CHARS_U)s:0-9]|%(PLX)s)\n                     (([%(PN_CHARS)s\\.:]|%(PLX)s)*\n                      ([%(PN_CHARS)s:]|%(PLX)s) )?' % dict(PN_CHARS_U=PN_CHARS_U_re, PN_CHARS=PN_CHARS_re, PLX=PLX_re), flags=X | UNICODE)

PN_LOCAL_ESC_re module-attribute

PN_LOCAL_ESC_re = '\\\\[_~\\.\\-!$&"\'()*+,;=/?#@%]'

PN_PREFIX module-attribute

PN_PREFIX = Regex('[%s](?:[%s\\.]*[%s])?' % (PN_CHARS_BASE_re, PN_CHARS_re, PN_CHARS_re), flags=U)

Path module-attribute

Path = Forward()

PathAlternative module-attribute

PathAlternative = Comp('PathAlternative', ParamList('part', PathSequence) + ZeroOrMore('|' + ParamList('part', PathSequence)))

PathElt module-attribute

PathElt = Comp('PathElt', Param('part', PathPrimary) + Optional(Param('mod', leaveWhitespace())))

PathEltOrInverse module-attribute

PathEltOrInverse = PathElt | Suppress('^') + Comp('PathEltOrInverse', Param('part', PathElt))

PathMod module-attribute

PathMod = Literal('?') | '*' | '+'

PathNegatedPropertySet module-attribute

PathNegatedPropertySet = Comp('PathNegatedPropertySet', ParamList('part', PathOneInPropertySet) | '(' + Optional(ParamList('part', PathOneInPropertySet) + ZeroOrMore('|' + ParamList('part', PathOneInPropertySet))) + ')')

PathOneInPropertySet module-attribute

PathOneInPropertySet = iri | A | Comp('InversePath', '^' + (iri | A))

PathPrimary module-attribute

PathPrimary = iri | A | Suppress('!') + PathNegatedPropertySet | Suppress('(') + Path + Suppress(')') | Comp('DistinctPath', CaselessKeyword('DISTINCT') + '(' + Param('part', Path) + ')')

PathSequence module-attribute

PathSequence = Comp('PathSequence', ParamList('part', PathEltOrInverse) + ZeroOrMore('/' + ParamList('part', PathEltOrInverse)))

PrefixDecl module-attribute

PrefixDecl = Comp('PrefixDecl', CaselessKeyword('PREFIX') + PNAME_NS + Param('iri', IRIREF))

PrefixedName module-attribute

PrefixedName = Comp('pname', PNAME_LN | PNAME_NS)

PrimaryExpression module-attribute

Prologue module-attribute

Prologue = Group(ZeroOrMore(BaseDecl | PrefixDecl))

PropertyList module-attribute

PropertyList = Optional(PropertyListNotEmpty)

PropertyListNotEmpty module-attribute

PropertyListNotEmpty = Verb + ObjectList + ZeroOrMore(';' + Optional(Verb + ObjectList))

PropertyListPath module-attribute

PropertyListPath = Optional(PropertyListPathNotEmpty)

PropertyListPathNotEmpty module-attribute

PropertyListPathNotEmpty = (VerbPath | VerbSimple) + ObjectListPath + ZeroOrMore(';' + Optional((VerbPath | VerbSimple) + ObjectListPath))

QuadData module-attribute

QuadData = '{' + Param('quads', Quads) + '}'

QuadPattern module-attribute

QuadPattern = '{' + Param('quads', Quads) + '}'

Quads module-attribute

Quads = Comp('Quads', Optional(TriplesTemplate) + ZeroOrMore(ParamList('quadsNotTriples', QuadsNotTriples) + Optional(Suppress('.')) + Optional(TriplesTemplate)))

QuadsNotTriples module-attribute

QuadsNotTriples = Comp('QuadsNotTriples', CaselessKeyword('GRAPH') + Param('term', VarOrIri) + '{' + Optional(TriplesTemplate) + '}')

Query module-attribute

QueryUnit module-attribute

QueryUnit = Query

RDFLiteral module-attribute

RDFLiteral = Comp('literal', Param('string', String) + Optional(Param('lang', leaveWhitespace()) | leaveWhitespace() + leaveWhitespace()))

RegexExpression module-attribute

RegexExpression = Comp('Builtin_REGEX', CaselessKeyword('REGEX') + '(' + Param('text', Expression) + ',' + Param('pattern', Expression) + Optional(',' + Param('flags', Expression)) + ')')

RelationalExpression module-attribute

RelationalExpression = setEvalFn(RelationalExpression)

STRING_LITERAL1 module-attribute

STRING_LITERAL1 = Regex("'(?:[^'\\n\\r\\\\]|\\\\['ntbrf\\\\])*'(?!')", flags=U)

STRING_LITERAL2 module-attribute

STRING_LITERAL2 = Regex('"(?:[^"\\n\\r\\\\]|\\\\["ntbrf\\\\])*"(?!")', flags=U)

STRING_LITERAL_LONG1 module-attribute

STRING_LITERAL_LONG1 = Regex("'''((?:'|'')?(?:[^'\\\\]|\\\\['ntbrf\\\\]))*'''")

STRING_LITERAL_LONG2 module-attribute

STRING_LITERAL_LONG2 = Regex('"""(?:(?:"|"")?(?:[^"\\\\]|\\\\["ntbrf\\\\]))*"""')

SelectClause module-attribute

SelectClause = CaselessKeyword('SELECT') + Optional(Param('modifier', CaselessKeyword('DISTINCT') | CaselessKeyword('REDUCED'))) + (OneOrMore(ParamList('projection', Comp('vars', Param('var', Var) | Literal('(') + Param('expr', Expression) + CaselessKeyword('AS') + Param('evar', Var) + ')'))) | '*')

SelectQuery module-attribute

SelectQuery = Comp('SelectQuery', SelectClause + ZeroOrMore(ParamList('datasetClause', DatasetClause)) + WhereClause + SolutionModifier + ValuesClause)

ServiceGraphPattern module-attribute

ServiceGraphPattern = Comp('ServiceGraphPattern', CaselessKeyword('SERVICE') + _Silent + Param('term', VarOrIri) + Param('graph', GroupGraphPattern))

SolutionModifier module-attribute

SolutionModifier = Optional(Param('groupby', GroupClause)) + Optional(Param('having', HavingClause)) + Optional(Param('orderby', OrderClause)) + Optional(Param('limitoffset', LimitOffsetClauses))

SourceSelector module-attribute

SourceSelector = iri

StrReplaceExpression module-attribute

StrReplaceExpression = setEvalFn(Builtin_REPLACE)

SubSelect module-attribute

SubSelect = Comp('SubSelect', SelectClause + WhereClause + SolutionModifier + ValuesClause)

SubstringExpression module-attribute

SubstringExpression = setEvalFn(Builtin_SUBSTR)

TriplesBlock module-attribute

TriplesBlock = Forward()

TriplesNode module-attribute

TriplesNode = Forward()

TriplesNodePath module-attribute

TriplesNodePath = Forward()

TriplesSameSubject module-attribute

TriplesSameSubjectPath module-attribute

TriplesTemplate module-attribute

TriplesTemplate = ParamList('triples', TriplesSameSubject) + ZeroOrMore(Suppress('.') + Optional(ParamList('triples', TriplesSameSubject)))

UnaryExpression module-attribute

UnaryExpression = setEvalFn(UnaryNot) | setEvalFn(UnaryPlus) | setEvalFn(UnaryMinus) | PrimaryExpression

Update module-attribute

Update = Forward()

Update1 module-attribute

UpdateUnit module-attribute

UpdateUnit = Comp('Update', Update)

UsingClause module-attribute

UsingClause = Comp('UsingClause', CaselessKeyword('USING') + (Param('default', iri) | CaselessKeyword('NAMED') + Param('named', iri)))

VAR1 module-attribute

VAR1 = Combine(Suppress('?') + VARNAME)

VAR2 module-attribute

VAR2 = Combine(Suppress('$') + VARNAME)

VARNAME module-attribute

VARNAME = Regex('[%s0-9][%s0-9·̀-ͯ‿-⁀]*' % (PN_CHARS_U_re, PN_CHARS_U_re), flags=U)

ValueLogical module-attribute

ValueLogical = RelationalExpression

ValuesClause module-attribute

ValuesClause = Optional(Param('valuesClause', Comp('ValuesClause', CaselessKeyword('VALUES') + DataBlock)))

Var module-attribute

Var = VAR1 | VAR2

VarOrIri module-attribute

VarOrIri = Var | iri

VarOrTerm module-attribute

VarOrTerm = Var | GraphTerm

Verb module-attribute

Verb = VarOrIri | A

VerbPath module-attribute

VerbPath = Path

VerbSimple module-attribute

VerbSimple = Var

WhereClause module-attribute

WhereClause = Optional(CaselessKeyword('WHERE')) + Param('where', GroupGraphPattern)

expandUnicodeEscapes_re module-attribute

expandUnicodeEscapes_re: Pattern = compile('\\\\u([0-9a-f]{4}(?:[0-9a-f]{4})?)', flags=I)

iri module-attribute

iriOrFunction module-attribute

iriOrFunction = setEvalFn(Function) | iri

expandBNodeTriples

expandBNodeTriples(terms: ParseResults) -> List[Any]

expand [ ?p ?o ] syntax for implicit bnodes

Source code in rdflib/plugins/sparql/parser.py
def expandBNodeTriples(terms: ParseResults) -> List[Any]:
    """
    expand [ ?p ?o ] syntax for implicit bnodes
    """
    # import pdb; pdb.set_trace()
    try:
        if DEBUG:
            print("Bnode terms", terms)
            print("1", terms[0])
            print("2", [rdflib.BNode()] + terms.asList()[0])
        return [expandTriples([rdflib.BNode()] + terms.asList()[0])]
    except Exception as e:
        if DEBUG:
            print(">>>>>>>>", e)
        raise

expandCollection

expandCollection(terms: ParseResults) -> List[List[Any]]

expand ( 1 2 3 ) notation for collections

Source code in rdflib/plugins/sparql/parser.py
def expandCollection(terms: ParseResults) -> List[List[Any]]:
    """
    expand ( 1 2 3 ) notation for collections
    """
    if DEBUG:
        print("Collection: ", terms)

    res: List[Any] = []
    other = []
    for x in terms:
        if isinstance(x, list):  # is this a [ .. ] ?
            other += x
            x = x[0]

        b = rdflib.BNode()
        if res:
            res += [res[-3], rdflib.RDF.rest, b, b, rdflib.RDF.first, x]
        else:
            res += [b, rdflib.RDF.first, x]
    res += [b, rdflib.RDF.rest, rdflib.RDF.nil]

    res += other

    if DEBUG:
        print("CollectionOut", res)
    return [res]

expandTriples

expandTriples(terms: ParseResults) -> List[Any]

Expand ; and , syntax for repeat predicates, subjects

Source code in rdflib/plugins/sparql/parser.py
def expandTriples(terms: ParseResults) -> List[Any]:
    """
    Expand ; and , syntax for repeat predicates, subjects
    """
    # import pdb; pdb.set_trace()
    last_subject, last_predicate = None, None  # Used for ; and ,
    try:
        res: List[Any] = []
        if DEBUG:
            print("Terms", terms)
        l_ = len(terms)
        for i, t in enumerate(terms):
            if t == ",":
                res.extend([last_subject, last_predicate])
            elif t == ";":
                if i + 1 == len(terms) or terms[i + 1] == ";" or terms[i + 1] == ".":
                    continue  # this semicolon is spurious
                res.append(last_subject)
            elif isinstance(t, list):
                # BlankNodePropertyList
                # is this bnode the object of previous triples?
                if (len(res) % 3) == 2:
                    res.append(t[0])
                # is this a single [] ?
                if len(t) > 1:
                    res += t  # Don't update last_subject/last_predicate
                # is this bnode the subject of more triples?
                if i + 1 < l_ and terms[i + 1] not in [
                    ".",
                    ",",
                    ";",
                ]:  # term might not be a string
                    last_subject, last_predicate = t[0], None
                    res.append(t[0])
            elif isinstance(t, ParseResults):
                res += t.asList()
            elif t != ".":
                res.append(t)
                if (len(res) % 3) == 1:
                    last_subject = t
                elif (len(res) % 3) == 2:
                    last_predicate = t
            if DEBUG:
                print(len(res), t)
        if DEBUG:
            import json

            print(json.dumps(res, indent=2))

        return res
        # print res
        # assert len(res)%3 == 0, \
        #       "Length of triple-list is not divisible by 3: %d!"%len(res)

        # return [tuple(res[i:i+3]) for i in range(len(res)/3)]
    except:
        if DEBUG:
            import traceback

            traceback.print_exc()
        raise

expandUnicodeEscapes

expandUnicodeEscapes(q: str) -> str

The syntax of the SPARQL Query Language is expressed over code points in Unicode [UNICODE]. The encoding is always UTF-8 [RFC3629]. Unicode code points may also be expressed using an \ uXXXX (U+0 to U+FFFF) or \ UXXXXXXXX syntax (for U+10000 onwards) where X is a hexadecimal digit [0-9A-F]

Source code in rdflib/plugins/sparql/parser.py
def expandUnicodeEscapes(q: str) -> str:
    r"""
    The syntax of the SPARQL Query Language is expressed over code points in Unicode [UNICODE]. The encoding is always UTF-8 [RFC3629].
    Unicode code points may also be expressed using an \ uXXXX (U+0 to U+FFFF) or \ UXXXXXXXX syntax (for U+10000 onwards) where X is a hexadecimal digit [0-9A-F]
    """

    def expand(m: re.Match) -> str:
        try:
            return chr(int(m.group(1), 16))
        except (ValueError, OverflowError) as e:
            raise ValueError("Invalid unicode code point: " + m.group(1)) from e

    return expandUnicodeEscapes_re.sub(expand, q)

neg

neg(literal: Literal) -> Literal
Source code in rdflib/plugins/sparql/parser.py
def neg(literal: rdflib.Literal) -> rdflib.Literal:
    return rdflib.Literal(-literal, datatype=literal.datatype)

parseQuery

parseQuery(q: Union[str, bytes, TextIO, BinaryIO]) -> ParseResults
Source code in rdflib/plugins/sparql/parser.py
def parseQuery(q: Union[str, bytes, TextIO, BinaryIO]) -> ParseResults:
    if hasattr(q, "read"):
        q = q.read()
    if isinstance(q, bytes):
        q = q.decode("utf-8")

    q = expandUnicodeEscapes(q)
    return Query.parseString(q, parseAll=True)

parseUpdate

parseUpdate(q: Union[str, bytes, TextIO, BinaryIO]) -> CompValue
Source code in rdflib/plugins/sparql/parser.py
def parseUpdate(q: Union[str, bytes, TextIO, BinaryIO]) -> CompValue:
    if hasattr(q, "read"):
        q = q.read()

    if isinstance(q, bytes):
        q = q.decode("utf-8")

    q = expandUnicodeEscapes(q)
    return UpdateUnit.parseString(q, parseAll=True)[0]

setDataType

setDataType(terms: Tuple[Any, Optional[str]]) -> Literal
Source code in rdflib/plugins/sparql/parser.py
def setDataType(terms: Tuple[Any, OptionalType[str]]) -> rdflib.Literal:
    return rdflib.Literal(terms[0], datatype=terms[1])

setLanguage

setLanguage(terms: Tuple[Any, Optional[str]]) -> Literal
Source code in rdflib/plugins/sparql/parser.py
def setLanguage(terms: Tuple[Any, OptionalType[str]]) -> rdflib.Literal:
    return rdflib.Literal(terms[0], lang=terms[1])