Skip to content

# `` parser

SPARQL 1.1 Parser

based on pyparsing

Functions:

- `expandBNodeTriples` –

  expand [ ?p ?o ] syntax for implicit bnodes

- `expandCollection` –

  expand ( 1 2 3 ) notation for collections

- `expandTriples` –

  Expand ; and , syntax for repeat predicates, subjects

- `expandUnicodeEscapes` –

  The syntax of the SPARQL Query Language is expressed over code points in Unicode [UNICODE]. The encoding is always UTF-8 [RFC3629].

- `neg` –
- `parseQuery` –
- `parseUpdate` –
- `setDataType` –
- `setLanguage` –

Attributes:

- `A` –
- `ANON` –
- `Add` –
- `AdditiveExpression` –
- `Aggregate` –
- `ArgList` –
- `AskQuery` –
- `BLANK_NODE_LABEL` –
- `BaseDecl` –
- `Bind` –
- `BlankNode` –
- `BlankNodePropertyList` –
- `BlankNodePropertyListPath` –
- `BooleanLiteral` –
- `BrackettedExpression` –
- `BuiltInCall` –
- `Clear` –
- `Collection` –
- `CollectionPath` –
- `ConditionalAndExpression` –
- `ConditionalOrExpression` –
- `Constraint` –
- `ConstructQuery` –
- `ConstructTemplate` –
- `ConstructTriples` –
- `Copy` –
- `Create` –
- `DEBUG` –
- `DECIMAL` –
- `DECIMAL_NEGATIVE` –
- `DECIMAL_POSITIVE` –
- `DOUBLE` –
- `DOUBLE_NEGATIVE` –
- `DOUBLE_POSITIVE` –
- `DataBlock` –
- `DataBlockValue` –
- `DatasetClause` –
- `DefaultGraphClause` –
- `DeleteClause` –
- `DeleteData` –
- `DeleteWhere` –
- `DescribeQuery` –
- `Drop` –
- `EXPONENT_re` –
- `ExistsFunc` –
- `Expression` –
- `ExpressionList` –
- `Filter` –
- `FunctionCall` –
- `GraphGraphPattern` –
- `GraphNode` –
- `GraphNodePath` –
- `GraphOrDefault` –
- `GraphPatternNotTriples` –
- `GraphRef` –
- `GraphRefAll` –
- `GraphTerm` –
- `GroupClause` –
- `GroupCondition` –
- `GroupGraphPattern` –
- `GroupGraphPatternSub` –
- `GroupOrUnionGraphPattern` –
- `HavingClause` –
- `HavingCondition` –
- `INTEGER` –
- `INTEGER_NEGATIVE` –
- `INTEGER_POSITIVE` –
- `IRIREF` –
- `InlineData` –
- `InlineDataFull` –
- `InlineDataOneVar` –
- `InsertClause` –
- `InsertData` –
- `Integer` –
- `LANGTAG` –
- `LimitClause` –
- `LimitOffsetClauses` –
- `Load` –
- `MinusGraphPattern` –
- `Modify` –
- `Move` –
- `MultiplicativeExpression` –
- `NIL` –
- `NamedGraphClause` –
- `NotExistsFunc` –
- `NumericExpression` –
- `NumericLiteral` –
- `NumericLiteralNegative` –
- `NumericLiteralPositive` –
- `NumericLiteralUnsigned` –
- `Object` –
- `ObjectList` –
- `ObjectListPath` –
- `ObjectPath` –
- `OffsetClause` –
- `OptionalGraphPattern` –
- `OrderClause` –
- `OrderCondition` –
- `PERCENT_re` –
- `PLX_re` –
- `PNAME_LN` –
- `PNAME_NS` –
- `PN_CHARS_BASE_re` –
- `PN_CHARS_U_re` –
- `PN_CHARS_re` –
- `PN_LOCAL` –
- `PN_LOCAL_ESC_re` –
- `PN_PREFIX` –
- `Path` –
- `PathAlternative` –
- `PathElt` –
- `PathEltOrInverse` –
- `PathMod` –
- `PathNegatedPropertySet` –
- `PathOneInPropertySet` –
- `PathPrimary` –
- `PathSequence` –
- `PrefixDecl` –
- `PrefixedName` –
- `PrimaryExpression` –
- `Prologue` –
- `PropertyList` –
- `PropertyListNotEmpty` –
- `PropertyListPath` –
- `PropertyListPathNotEmpty` –
- `QuadData` –
- `QuadPattern` –
- `Quads` –
- `QuadsNotTriples` –
- `Query` –
- `QueryUnit` –
- `RDFLiteral` –
- `RegexExpression` –
- `RelationalExpression` –
- `STRING_LITERAL1` –
- `STRING_LITERAL2` –
- `STRING_LITERAL_LONG1` –
- `STRING_LITERAL_LONG2` –
- `SelectClause` –
- `SelectQuery` –
- `ServiceGraphPattern` –
- `SolutionModifier` –
- `SourceSelector` –
- `StrReplaceExpression` –
- `String` –
- `SubSelect` –
- `SubstringExpression` –
- `TriplesBlock` –
- `TriplesNode` –
- `TriplesNodePath` –
- `TriplesSameSubject` –
- `TriplesSameSubjectPath` –
- `TriplesTemplate` –
- `UnaryExpression` –
- `Update` –
- `Update1` –
- `UpdateUnit` –
- `UsingClause` –
- `VAR1` –
- `VAR2` –
- `VARNAME` –
- `ValueLogical` –
- `ValuesClause` –
- `Var` –
- `VarOrIri` –
- `VarOrTerm` –
- `Verb` –
- `VerbPath` –
- `VerbSimple` –
- `WhereClause` –
- `expandUnicodeEscapes_re` (`Pattern`) –
- `iri` –
- `iriOrFunction` –

## `` 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`

    Constraint = BrackettedExpression | BuiltInCall | FunctionCall

## `` 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`

    DataBlock = InlineDataOneVar | InlineDataFull

## `` 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`

    GraphPatternNotTriples = GroupOrUnionGraphPattern | OptionalGraphPattern | MinusGraphPattern | GraphGraphPattern | ServiceGraphPattern | Filter | Bind | InlineData

## `` 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`

    GraphTerm = iri | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | NIL

## `` 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`

    NumericLiteral = NumericLiteralUnsigned | NumericLiteralPositive | NumericLiteralNegative

## `` 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`

    PrimaryExpression = BrackettedExpression | BuiltInCall | iriOrFunction | RDFLiteral | NumericLiteral | BooleanLiteral | Var

## `` 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`

    Query = Prologue + (SelectQuery | ConstructQuery | DescribeQuery | AskQuery)

## `` 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)

## `` String `module-attribute`

    String = STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2 | STRING_LITERAL1 | STRING_LITERAL2

## `` 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`

    TriplesSameSubject = VarOrTerm + PropertyListNotEmpty | TriplesNode + PropertyList

## `` TriplesSameSubjectPath `module-attribute`

    TriplesSameSubjectPath = VarOrTerm + PropertyListPathNotEmpty | TriplesNodePath + PropertyListPath

## `` 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`

    Update1 = Load | Clear | Drop | Add | Move | Copy | Create | InsertData | DeleteData | DeleteWhere | Modify

## `` 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`

    iri = IRIREF | PrefixedName

## `` 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`

    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134

    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`

    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

    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`

     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

    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`

    1531
    1532
    1533
    1534
    1535
    1536
    1537
    1538
    1539
    1540
    1541
    1542
    1543

    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`

    45
    46

    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`

    1546
    1547
    1548
    1549
    1550
    1551
    1552
    1553

    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`

    1556
    1557
    1558
    1559
    1560
    1561
    1562
    1563
    1564

    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`

    53
    54

    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`

    49
    50

    def setLanguage(terms: Tuple[Any, OptionalType[str]]) -> rdflib.Literal:
        return rdflib.Literal(terms[0], lang=terms[1])