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', Keyword('ADD') + _Silent + GraphOrDefault + Keyword('TO') + GraphOrDefault)

AdditiveExpression module-attribute

AdditiveExpression = Comp('AdditiveExpression', Param('expr', MultiplicativeExpression) + ZeroOrMore(ParamList('op', '+') + ParamList('other', MultiplicativeExpression) | ParamList('op', '-') + ParamList('other', MultiplicativeExpression))).setEvalFn(op.AdditiveExpression)

Aggregate module-attribute

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

ArgList module-attribute

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

AskQuery module-attribute

AskQuery = Comp('AskQuery', Keyword('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=re.U)

BaseDecl module-attribute

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

Bind module-attribute

Bind = Comp('Bind', Keyword('BIND') + '(' + Param('expr', Expression) + Keyword('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 = Keyword('true').set_parse_action(lambda: rdflib.Literal(True)) | Keyword('false').set_parse_action(lambda: rdflib.Literal(False))

BrackettedExpression module-attribute

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

BuiltInCall module-attribute

BuiltInCall = Aggregate | Comp('Builtin_STR', Keyword('STR') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_STR) | Comp('Builtin_LANG', Keyword('LANG') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_LANG) | Comp('Builtin_LANGMATCHES', Keyword('LANGMATCHES') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ')').setEvalFn(op.Builtin_LANGMATCHES) | Comp('Builtin_DATATYPE', Keyword('DATATYPE') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_DATATYPE) | Comp('Builtin_BOUND', Keyword('BOUND') + '(' + Param('arg', Var) + ')').setEvalFn(op.Builtin_BOUND) | Comp('Builtin_IRI', Keyword('IRI') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_IRI) | Comp('Builtin_URI', Keyword('URI') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_IRI) | Comp('Builtin_BNODE', Keyword('BNODE') + ('(' + Param('arg', Expression) + ')' | NIL)).setEvalFn(op.Builtin_BNODE) | Comp('Builtin_RAND', Keyword('RAND') + NIL).setEvalFn(op.Builtin_RAND) | Comp('Builtin_ABS', Keyword('ABS') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_ABS) | Comp('Builtin_CEIL', Keyword('CEIL') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_CEIL) | Comp('Builtin_FLOOR', Keyword('FLOOR') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_FLOOR) | Comp('Builtin_ROUND', Keyword('ROUND') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_ROUND) | Comp('Builtin_CONCAT', Keyword('CONCAT') + Param('arg', ExpressionList)).setEvalFn(op.Builtin_CONCAT) | SubstringExpression | Comp('Builtin_STRLEN', Keyword('STRLEN') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_STRLEN) | StrReplaceExpression | Comp('Builtin_UCASE', Keyword('UCASE') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_UCASE) | Comp('Builtin_LCASE', Keyword('LCASE') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_LCASE) | Comp('Builtin_ENCODE_FOR_URI', Keyword('ENCODE_FOR_URI') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_ENCODE_FOR_URI) | Comp('Builtin_CONTAINS', Keyword('CONTAINS') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ')').setEvalFn(op.Builtin_CONTAINS) | Comp('Builtin_STRSTARTS', Keyword('STRSTARTS') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ')').setEvalFn(op.Builtin_STRSTARTS) | Comp('Builtin_STRENDS', Keyword('STRENDS') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ')').setEvalFn(op.Builtin_STRENDS) | Comp('Builtin_STRBEFORE', Keyword('STRBEFORE') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ')').setEvalFn(op.Builtin_STRBEFORE) | Comp('Builtin_STRAFTER', Keyword('STRAFTER') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ')').setEvalFn(op.Builtin_STRAFTER) | Comp('Builtin_YEAR', Keyword('YEAR') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_YEAR) | Comp('Builtin_MONTH', Keyword('MONTH') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_MONTH) | Comp('Builtin_DAY', Keyword('DAY') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_DAY) | Comp('Builtin_HOURS', Keyword('HOURS') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_HOURS) | Comp('Builtin_MINUTES', Keyword('MINUTES') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_MINUTES) | Comp('Builtin_SECONDS', Keyword('SECONDS') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_SECONDS) | Comp('Builtin_TIMEZONE', Keyword('TIMEZONE') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_TIMEZONE) | Comp('Builtin_TZ', Keyword('TZ') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_TZ) | Comp('Builtin_NOW', Keyword('NOW') + NIL).setEvalFn(op.Builtin_NOW) | Comp('Builtin_UUID', Keyword('UUID') + NIL).setEvalFn(op.Builtin_UUID) | Comp('Builtin_STRUUID', Keyword('STRUUID') + NIL).setEvalFn(op.Builtin_STRUUID) | Comp('Builtin_MD5', Keyword('MD5') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_MD5) | Comp('Builtin_SHA1', Keyword('SHA1') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_SHA1) | Comp('Builtin_SHA256', Keyword('SHA256') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_SHA256) | Comp('Builtin_SHA384', Keyword('SHA384') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_SHA384) | Comp('Builtin_SHA512', Keyword('SHA512') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_SHA512) | Comp('Builtin_COALESCE', Keyword('COALESCE') + Param('arg', ExpressionList)).setEvalFn(op.Builtin_COALESCE) | Comp('Builtin_IF', Keyword('IF') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ',' + Param('arg3', Expression) + ')').setEvalFn(op.Builtin_IF) | Comp('Builtin_STRLANG', Keyword('STRLANG') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ')').setEvalFn(op.Builtin_STRLANG) | Comp('Builtin_STRDT', Keyword('STRDT') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ')').setEvalFn(op.Builtin_STRDT) | Comp('Builtin_sameTerm', Keyword('sameTerm') + '(' + Param('arg1', Expression) + ',' + Param('arg2', Expression) + ')').setEvalFn(op.Builtin_sameTerm) | Comp('Builtin_isIRI', Keyword('isIRI') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_isIRI) | Comp('Builtin_isURI', Keyword('isURI') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_isIRI) | Comp('Builtin_isBLANK', Keyword('isBLANK') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_isBLANK) | Comp('Builtin_isLITERAL', Keyword('isLITERAL') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_isLITERAL) | Comp('Builtin_isNUMERIC', Keyword('isNUMERIC') + '(' + Param('arg', Expression) + ')').setEvalFn(op.Builtin_isNUMERIC) | RegexExpression | ExistsFunc | NotExistsFunc

Clear module-attribute

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

Collection module-attribute

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

CollectionPath module-attribute

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

ConditionalAndExpression module-attribute

ConditionalAndExpression = Comp('ConditionalAndExpression', Param('expr', ValueLogical) + ZeroOrMore('&&' + ParamList('other', ValueLogical))).setEvalFn(op.ConditionalAndExpression)

ConditionalOrExpression module-attribute

ConditionalOrExpression = Comp('ConditionalOrExpression', Param('expr', ConditionalAndExpression) + ZeroOrMore('||' + ParamList('other', ConditionalAndExpression))).setEvalFn(op.ConditionalOrExpression)

Constraint module-attribute

ConstructQuery module-attribute

ConstructQuery = Comp('ConstructQuery', Keyword('CONSTRUCT') + (ConstructTemplate + ZeroOrMore(ParamList('datasetClause', DatasetClause)) + WhereClause + SolutionModifier + ValuesClause | ZeroOrMore(ParamList('datasetClause', DatasetClause)) + Keyword('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', Keyword('COPY') + _Silent + GraphOrDefault + Keyword('TO') + GraphOrDefault)

Create module-attribute

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

DEBUG module-attribute

DEBUG = False

DECIMAL module-attribute

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

DECIMAL_NEGATIVE module-attribute

DECIMAL_NEGATIVE = Suppress('-') + DECIMAL.copy().leave_whitespace()

DECIMAL_POSITIVE module-attribute

DECIMAL_POSITIVE = Suppress('+') + DECIMAL.copy().leave_whitespace()

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('-') + DOUBLE.copy().leave_whitespace()

DOUBLE_POSITIVE module-attribute

DOUBLE_POSITIVE = Suppress('+') + DOUBLE.copy().leave_whitespace()

DataBlock module-attribute

DataBlockValue module-attribute

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

DatasetClause module-attribute

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

DefaultGraphClause module-attribute

DefaultGraphClause = SourceSelector

DeleteClause module-attribute

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

DeleteData module-attribute

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

DeleteWhere module-attribute

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

DescribeQuery module-attribute

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

Drop module-attribute

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

EXPONENT_re module-attribute

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

ExistsFunc module-attribute

ExistsFunc = Comp('Builtin_EXISTS', Keyword('EXISTS') + Param('graph', GroupGraphPattern)).setEvalFn(op.Builtin_EXISTS)

Expression module-attribute

Expression = Forward()

ExpressionList module-attribute

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

Filter module-attribute

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

FunctionCall module-attribute

FunctionCall = Comp('Function', Param('iri', iri) + ArgList).setEvalFn(op.Function)

GraphGraphPattern module-attribute

GraphGraphPattern = Comp('GraphGraphPattern', Keyword('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', Keyword('DEFAULT')) | Optional(Keyword('GRAPH')) + ParamList('graph', iri)

GraphPatternNotTriples module-attribute

GraphRef module-attribute

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

GraphRefAll module-attribute

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

GraphTerm module-attribute

GroupClause module-attribute

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

GroupCondition module-attribute

GroupCondition = BuiltInCall | FunctionCall | Comp('GroupAs', '(' + Param('expr', Expression) + Optional(Keyword('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(Keyword('UNION') + ParamList('graph', GroupGraphPattern)))

HavingClause module-attribute

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

HavingCondition module-attribute

HavingCondition = Constraint

INTEGER module-attribute

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

INTEGER_NEGATIVE module-attribute

INTEGER_NEGATIVE = Suppress('-') + INTEGER.copy().leave_whitespace()

INTEGER_POSITIVE module-attribute

INTEGER_POSITIVE = Suppress('+') + INTEGER.copy().leave_whitespace()

IRIREF module-attribute

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

InlineData module-attribute

InlineData = Comp('InlineData', Keyword('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', Keyword('INSERT') + QuadPattern)

InsertData module-attribute

InsertData = Comp('InsertData', Keyword('INSERT') + Keyword('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 = Keyword('LIMIT') + Param('limit', INTEGER)

LimitOffsetClauses module-attribute

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

Load module-attribute

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

MinusGraphPattern module-attribute

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

Modify module-attribute

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

Move module-attribute

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

MultiplicativeExpression module-attribute

MultiplicativeExpression = Comp('MultiplicativeExpression', Param('expr', UnaryExpression) + ZeroOrMore(ParamList('op', '*') + ParamList('other', UnaryExpression) | ParamList('op', '/') + ParamList('other', UnaryExpression))).setEvalFn(op.MultiplicativeExpression)

NIL module-attribute

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

NamedGraphClause module-attribute

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

NotExistsFunc module-attribute

NotExistsFunc = Comp('Builtin_NOTEXISTS', Keyword('NOT') + Keyword('EXISTS') + Param('graph', GroupGraphPattern)).setEvalFn(op.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 = Keyword('OFFSET') + Param('offset', INTEGER)

OptionalGraphPattern module-attribute

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

OrderClause module-attribute

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

OrderCondition module-attribute

OrderCondition = Comp('OrderCondition', Param('order', Keyword('ASC') | Keyword('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', PN_LOCAL.leave_whitespace())

PNAME_NS module-attribute

PNAME_NS = Optional(Param('prefix', PN_PREFIX)) + Suppress(':').leave_whitespace()

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=re.X | re.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=re.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', PathMod.leave_whitespace())))

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', Keyword('DISTINCT') + '(' + Param('part', Path) + ')')

PathSequence module-attribute

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

PrefixDecl module-attribute

PrefixDecl = Comp('PrefixDecl', Keyword('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', Keyword('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', LANGTAG.leave_whitespace()) | Literal('^^').leave_whitespace() + Param('datatype', iri).leave_whitespace()))

RegexExpression module-attribute

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

RelationalExpression module-attribute

RelationalExpression = Comp('RelationalExpression', Param('expr', NumericExpression) + Optional(Param('op', '=') + Param('other', NumericExpression) | Param('op', '!=') + Param('other', NumericExpression) | Param('op', '<') + Param('other', NumericExpression) | Param('op', '>') + Param('other', NumericExpression) | Param('op', '<=') + Param('other', NumericExpression) | Param('op', '>=') + Param('other', NumericExpression) | Param('op', Keyword('IN')) + Param('other', ExpressionList) | Param('op', Combine(Keyword('NOT') + Keyword('IN'), adjacent=False, **(combine_join_kwargs(' ')))) + Param('other', ExpressionList))).setEvalFn(op.RelationalExpression)

STRING_LITERAL1 module-attribute

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

STRING_LITERAL2 module-attribute

STRING_LITERAL2 = Regex('"(?:[^"\\n\\r\\\\]|\\\\["ntbrf\\\\])*"(?!")', flags=re.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 = Keyword('SELECT') + Optional(Param('modifier', Keyword('DISTINCT') | Keyword('REDUCED'))) + (OneOrMore(ParamList('projection', Comp('vars', Param('var', Var) | Literal('(') + Param('expr', Expression) + Keyword('AS') + Param('evar', Var) + ')'))) | '*')

SelectQuery module-attribute

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

ServiceGraphPattern module-attribute

ServiceGraphPattern = Comp('ServiceGraphPattern', Keyword('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 = Comp('Builtin_REPLACE', Keyword('REPLACE') + '(' + Param('arg', Expression) + ',' + Param('pattern', Expression) + ',' + Param('replacement', Expression) + Optional(',' + Param('flags', Expression)) + ')').setEvalFn(op.Builtin_REPLACE)

SubSelect module-attribute

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

SubstringExpression module-attribute

SubstringExpression = Comp('Builtin_SUBSTR', Keyword('SUBSTR') + '(' + Param('arg', Expression) + ',' + Param('start', Expression) + Optional(',' + Param('length', Expression)) + ')').setEvalFn(op.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 = Comp('UnaryNot', '!' + Param('expr', PrimaryExpression)).setEvalFn(op.UnaryNot) | Comp('UnaryPlus', '+' + Param('expr', PrimaryExpression)).setEvalFn(op.UnaryPlus) | Comp('UnaryMinus', '-' + Param('expr', PrimaryExpression)).setEvalFn(op.UnaryMinus) | PrimaryExpression

Update module-attribute

Update = Forward()

Update1 module-attribute

UpdateUnit module-attribute

UpdateUnit = Comp('Update', Update)

UsingClause module-attribute

UsingClause = Comp('UsingClause', Keyword('USING') + (Param('default', iri) | Keyword('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=re.U)

ValueLogical module-attribute

ValueLogical = RelationalExpression

ValuesClause module-attribute

ValuesClause = Optional(Param('valuesClause', Comp('ValuesClause', Keyword('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(Keyword('WHERE')) + Param('where', GroupGraphPattern)

expandUnicodeEscapes_re module-attribute

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

iri module-attribute

iriOrFunction module-attribute

iriOrFunction = Comp('Function', Param('iri', iri) + ArgList).setEvalFn(op.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.as_list()[0])
        return [expandTriples([rdflib.BNode()] + terms.as_list()[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.as_list()
            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.parse_string(q, parse_all=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.parse_string(q, parse_all=True)[0]

setDataType

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

setLanguage

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