@kurrawongai/codemirror-lang-sparql12 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ import * as terms from './sparql.grammar.terms';
2
+
3
+ /**
4
+ * SPARQL's keywords are case-insensitive and not reserved.
5
+ *
6
+ * `SELECT`, `select` and `SeLeCt` are the same keyword; `select:x` is a
7
+ * prefixed name and `?select` is a variable, neither of which is a keyword at
8
+ * all. That combination is why the grammar lexes one `Word` token and hands it
9
+ * here rather than declaring 125 case-insensitive terminals: a terminal per
10
+ * keyword would have to spell out every letter's two cases, and would then
11
+ * overlap with `PNameLN` on every keyword that also starts a prefix.
12
+ *
13
+ * The keyword list is therefore not written twice. The grammar's specialize
14
+ * block names one term per keyword as `Kw` + the keyword in upper case, and
15
+ * this map is derived from those term names — so adding a keyword to the
16
+ * grammar is the only edit needed, and a term that is declared but unreachable
17
+ * is impossible to forget about.
18
+ */
19
+ const BY_WORD: Record<string, number> = Object.create(null);
20
+
21
+ for (const [name, id] of Object.entries(terms as unknown as Record<string, number>)) {
22
+ if (name.startsWith('Kw') && typeof id === 'number') BY_WORD[name.slice(2).toLowerCase()] = id;
23
+ }
24
+
25
+ /** The specializer the grammar calls for every `Word`. `-1` means "not a keyword". */
26
+ export function keyword(value: string): number {
27
+ const found = BY_WORD[value.toLowerCase()];
28
+ return found === undefined ? -1 : found;
29
+ }
30
+
31
+ /** Every keyword the grammar knows, lower-cased. Used by the highlight and completion tests. */
32
+ export const KEYWORDS: readonly string[] = Object.keys(BY_WORD).sort();
33
+
34
+ /** The node names the grammar gives keywords, for `styleTags`. */
35
+ export const KEYWORD_NODE_NAMES: readonly string[] = Object.keys(
36
+ terms as unknown as Record<string, number>
37
+ )
38
+ .filter((name) => name.startsWith('Kw'))
39
+ .sort();
@@ -0,0 +1,486 @@
1
+ // SPARQL 1.2 (query and update) and SRL, in one grammar with two entry points.
2
+ //
3
+ // `SparqlUnit` is the SPARQL 1.2 grammar's QueryUnit/UpdateUnit; `SrlUnit` is
4
+ // an SRL rule set. They share every production below the rule body, which is
5
+ // the reason they are one file: SPARQL and SRL can then never disagree about
6
+ // what a term is, and `codemirror-lang-srl` is a `parser.configure({ top })`
7
+ // away rather than a second grammar to keep in step.
8
+ //
9
+ // Keywords are case-insensitive and are not reserved: `SELECT` is a keyword,
10
+ // `select:x` is a prefixed name and `?select` is a variable. That is handled by
11
+ // lexing one `Word` token and specializing it in `keywords.ts`, so the keyword
12
+ // list lives in one place and mixed casing (`SeLeCt`) works like any other.
13
+ //
14
+ // Production names follow the W3C grammar. See README.md for the pinned spec
15
+ // revisions and for the one place SRL's names had to differ.
16
+
17
+ @top SparqlUnit { Prologue (Query | Update)? }
18
+ @top SrlUnit { RuleSet }
19
+
20
+ @skip { whitespace | Comment }
21
+
22
+ // ------------------------------------------------------------------ prologue
23
+
24
+ Prologue { (BaseDecl | PrefixDecl | VersionDecl)* }
25
+ BaseDecl { KwBASE IRIRef }
26
+ PrefixDecl { KwPREFIX PNameNS IRIRef }
27
+ VersionDecl { KwVERSION VersionSpecifier }
28
+
29
+ // --------------------------------------------------------------------- query
30
+
31
+ Query { (SelectQuery | ConstructQuery | DescribeQuery | AskQuery) ValuesClause? }
32
+
33
+ SelectQuery { SelectClause DatasetClause* WhereClause SolutionModifier }
34
+ SubSelect { SelectClause WhereClause SolutionModifier ValuesClause? }
35
+
36
+ SelectClause {
37
+ KwSELECT (KwDISTINCT | KwREDUCED)? ((Var | ExpressionAs)+ | "*")
38
+ }
39
+ ExpressionAs { "(" Expression KwAS Var ")" }
40
+
41
+ ConstructQuery {
42
+ KwCONSTRUCT (
43
+ ConstructTemplate DatasetClause* WhereClause SolutionModifier |
44
+ DatasetClause* KwWHERE "{" TriplesTemplate? "}" SolutionModifier
45
+ )
46
+ }
47
+
48
+ DescribeQuery { KwDESCRIBE (varOrIri+ | "*") DatasetClause* WhereClause? SolutionModifier }
49
+ AskQuery { KwASK DatasetClause* WhereClause SolutionModifier }
50
+
51
+ DatasetClause { KwFROM (DefaultGraphClause | NamedGraphClause) }
52
+ DefaultGraphClause { iri }
53
+ NamedGraphClause { KwNAMED iri }
54
+
55
+ WhereClause { KwWHERE? GroupGraphPattern }
56
+
57
+ SolutionModifier { GroupClause? HavingClause? OrderClause? limitOffsetClauses? }
58
+ GroupClause { KwGROUP KwBY GroupCondition+ }
59
+ GroupCondition { BuiltInCall | FunctionCall | "(" Expression (KwAS Var)? ")" | Var }
60
+ HavingClause { KwHAVING havingCondition+ }
61
+ havingCondition { Constraint }
62
+ OrderClause { KwORDER KwBY OrderCondition+ }
63
+ OrderCondition { (KwASC | KwDESC) BrackettedExpression | Constraint | Var }
64
+ limitOffsetClauses { LimitClause OffsetClause? | OffsetClause LimitClause? }
65
+ LimitClause { KwLIMIT Integer }
66
+ OffsetClause { KwOFFSET Integer }
67
+ ValuesClause { KwVALUES DataBlock }
68
+
69
+ // -------------------------------------------------------------------- update
70
+
71
+ // [29] is recursive — `Update ::= Prologue (Update1 (';' Update)?)?` — and the
72
+ // recursion is load-bearing twice over: a prologue may appear after each `;`,
73
+ // and a *trailing* `;` is allowed while `;;` is not. Flattening this to
74
+ // `(";" Prologue update1?)*` accepts `;;`, which the suite rejects.
75
+ Update { update1 (";" updateTail?)? }
76
+ updateTail { Prologue update1 (";" updateTail?)? }
77
+
78
+ update1 {
79
+ Load | Clear | Drop | Add | Move | Copy | Create |
80
+ InsertData | DeleteData | DeleteWhere | Modify
81
+ }
82
+
83
+ Load { KwLOAD KwSILENT? iri (KwINTO GraphRef)? }
84
+ Clear { KwCLEAR KwSILENT? graphRefAll }
85
+ Drop { KwDROP KwSILENT? graphRefAll }
86
+ Create { KwCREATE KwSILENT? GraphRef }
87
+ Add { KwADD KwSILENT? graphOrDefault KwTO graphOrDefault }
88
+ Move { KwMOVE KwSILENT? graphOrDefault KwTO graphOrDefault }
89
+ Copy { KwCOPY KwSILENT? graphOrDefault KwTO graphOrDefault }
90
+ InsertData { KwINSERT KwDATA QuadData }
91
+ DeleteData { KwDELETE KwDATA QuadData }
92
+ DeleteWhere { KwDELETE KwWHERE QuadPattern }
93
+ Modify {
94
+ (KwWITH iri)? (DeleteClause InsertClause? | InsertClause) UsingClause* KwWHERE GroupGraphPattern
95
+ }
96
+ DeleteClause { KwDELETE QuadPattern }
97
+ InsertClause { KwINSERT QuadPattern }
98
+ UsingClause { KwUSING (iri | KwNAMED iri) }
99
+
100
+ graphOrDefault { KwDEFAULT | KwGRAPH? iri }
101
+ GraphRef { KwGRAPH iri }
102
+ graphRefAll { GraphRef | KwDEFAULT | KwNAMED | KwALL }
103
+
104
+ QuadPattern { "{" Quads "}" }
105
+ QuadData { "{" Quads "}" }
106
+ Quads { TriplesTemplate? (QuadsNotTriples "."? TriplesTemplate?)* }
107
+ QuadsNotTriples { KwGRAPH varOrIri "{" TriplesTemplate? "}" }
108
+ TriplesTemplate { TriplesSameSubject ("." TriplesTemplate?)? }
109
+
110
+ // ------------------------------------------------------------ graph patterns
111
+
112
+ GroupGraphPattern { "{" (SubSelect | GroupGraphPatternSub) "}" }
113
+ GroupGraphPatternSub { TriplesBlock? (graphPatternNotTriples "."? TriplesBlock?)* }
114
+ TriplesBlock { TriplesSameSubjectPath ("." TriplesBlock?)? }
115
+
116
+ graphPatternNotTriples {
117
+ GroupOrUnionGraphPattern | OptionalGraphPattern | MinusGraphPattern |
118
+ GraphGraphPattern | ServiceGraphPattern | Filter | Bind | InlineData
119
+ }
120
+
121
+ OptionalGraphPattern { KwOPTIONAL GroupGraphPattern }
122
+ GraphGraphPattern { KwGRAPH varOrIri GroupGraphPattern }
123
+ ServiceGraphPattern { KwSERVICE KwSILENT? varOrIri GroupGraphPattern }
124
+ MinusGraphPattern { KwMINUS GroupGraphPattern }
125
+ GroupOrUnionGraphPattern { GroupGraphPattern (KwUNION GroupGraphPattern)* }
126
+ Bind { KwBIND "(" Expression KwAS Var ")" }
127
+ InlineData { KwVALUES DataBlock }
128
+ Filter { KwFILTER Constraint }
129
+
130
+ DataBlock { InlineDataOneVar | InlineDataFull }
131
+ InlineDataOneVar { Var "{" DataBlockValue* "}" }
132
+ InlineDataFull { (Nil | "(" Var* ")") "{" ("(" DataBlockValue* ")" | Nil)* "}" }
133
+ DataBlockValue { iri | RDFLiteral | NumericLiteral | BooleanLiteral | KwUNDEF | TripleTermData }
134
+
135
+ Constraint { BrackettedExpression | BuiltInCall | FunctionCall }
136
+ FunctionCall { iri ArgList }
137
+ ArgList { Nil | "(" KwDISTINCT? Expression ("," Expression)* ")" }
138
+ ExpressionList { Nil | "(" Expression ("," Expression)* ")" }
139
+
140
+ ConstructTemplate { "{" ConstructTriples? "}" }
141
+ ConstructTriples { TriplesSameSubject ("." ConstructTriples?)? }
142
+
143
+ // -------------------------------------------------------------------- triples
144
+
145
+ TriplesSameSubject {
146
+ varOrTerm PropertyListNotEmpty |
147
+ triplesNode PropertyListNotEmpty? |
148
+ ReifiedTriple PropertyListNotEmpty?
149
+ }
150
+
151
+ PropertyListNotEmpty { Verb ObjectList (";" (Verb ObjectList)?)* }
152
+ Verb { varOrIri | KwA }
153
+ ObjectList { Object ("," Object)* }
154
+ Object { graphNode Annotation? }
155
+
156
+ TriplesSameSubjectPath {
157
+ varOrTerm PropertyListPathNotEmpty |
158
+ triplesNodePath PropertyListPathNotEmpty? |
159
+ ReifiedTriple PropertyListPathNotEmpty?
160
+ }
161
+
162
+ PropertyListPathNotEmpty {
163
+ (VerbPath | VerbSimple) ObjectListPath (";" ((VerbPath | VerbSimple) ObjectList)?)*
164
+ }
165
+ VerbPath { Path }
166
+ VerbSimple { Var }
167
+ ObjectListPath { ObjectPath ("," ObjectPath)* }
168
+ ObjectPath { graphNodePath AnnotationPath? }
169
+
170
+ Path { PathAlternative }
171
+ PathAlternative { PathSequence ("|" PathSequence)* }
172
+ PathSequence { PathEltOrInverse ("/" PathEltOrInverse)* }
173
+ PathElt { PathPrimary PathMod? }
174
+ PathEltOrInverse { PathElt | "^" PathElt }
175
+ PathMod { "?" | "*" | "+" }
176
+ PathPrimary { iri | KwA | NotOp PathNegatedPropertySet | "(" Path ")" }
177
+ PathNegatedPropertySet {
178
+ PathOneInPropertyPath | "(" (PathOneInPropertyPath ("|" PathOneInPropertyPath)*)? ")"
179
+ }
180
+ PathOneInPropertyPath { iri | KwA | "^" (iri | KwA) }
181
+
182
+ triplesNode { Collection | BlankNodePropertyList }
183
+ BlankNodePropertyList { "[" PropertyListNotEmpty "]" }
184
+ triplesNodePath { CollectionPath | BlankNodePropertyListPath }
185
+ BlankNodePropertyListPath { "[" PropertyListPathNotEmpty "]" }
186
+ Collection { "(" graphNode+ ")" }
187
+ CollectionPath { "(" graphNodePath+ ")" }
188
+ graphNode { varOrTerm | triplesNode | ReifiedTriple }
189
+ graphNodePath { varOrTerm | triplesNodePath | ReifiedTriple }
190
+
191
+ varOrTerm { Var | iri | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | Nil | TripleTerm }
192
+ varOrIri { Var | iri }
193
+ Var { Var1 | Var2 }
194
+
195
+ // ---------------------------------------------------- RDF 1.2 term additions
196
+
197
+ // A literal can never be a subject, in any of the four bracketed forms, and
198
+ // the three restricted forms each drop something more: `VALUES` data may not
199
+ // nest a triple term in subject position, and an expression's triple term may
200
+ // hold neither a nested triple term nor a blank node.
201
+
202
+ ReifiedTriple { "<<" rtSubject Verb rtObject Reifier? ">>" }
203
+ rtSubject { Var | iri | BlankNode | ReifiedTriple | TripleTerm }
204
+ rtObject {
205
+ Var | iri | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | TripleTerm | ReifiedTriple
206
+ }
207
+
208
+ Reifier { "~" varOrReifierId? }
209
+ varOrReifierId { Var | iri | BlankNode }
210
+
211
+ TripleTerm { "<<(" ttSubject Verb ttObject ")>>" }
212
+ ttSubject { Var | iri | BlankNode | TripleTerm }
213
+ ttObject { Var | iri | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | TripleTerm }
214
+
215
+ TripleTermData { "<<(" ttdSubject (iri | KwA) ttdObject ")>>" }
216
+ ttdSubject { iri | BlankNode }
217
+ ttdObject { iri | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | TripleTermData }
218
+
219
+ Annotation { (Reifier | AnnotationBlock)+ }
220
+ AnnotationBlock { "{|" PropertyListNotEmpty "|}" }
221
+ AnnotationPath { (Reifier | AnnotationBlockPath)+ }
222
+ AnnotationBlockPath { "{|" PropertyListPathNotEmpty "|}" }
223
+
224
+ ExprTripleTerm { "<<(" etSubject Verb etObject ")>>" }
225
+ etSubject { Var | iri }
226
+ etObject { Var | iri | RDFLiteral | NumericLiteral | BooleanLiteral | ExprTripleTerm }
227
+
228
+ // ----------------------------------------------------------------- expressions
229
+
230
+ Expression { ConditionalOrExpression }
231
+ ConditionalOrExpression { ConditionalAndExpression (OrOp ConditionalAndExpression)* }
232
+ ConditionalAndExpression { valueLogical (AndOp valueLogical)* }
233
+ valueLogical { RelationalExpression }
234
+ RelationalExpression {
235
+ numericExpression (
236
+ CompareOp numericExpression |
237
+ KwIN ExpressionList |
238
+ KwNOT KwIN ExpressionList
239
+ )?
240
+ }
241
+ numericExpression { AdditiveExpression }
242
+
243
+ // [115]'s signed-literal alternative is why the numeric tokens carry their
244
+ // sign: `?x -1` is an addition whose right operand is the literal `-1`, while
245
+ // `?x - 1` is an addition with an operator. Both must parse.
246
+ AdditiveExpression {
247
+ MultiplicativeExpression (
248
+ ArithOp MultiplicativeExpression |
249
+ (NumericLiteralPositive | NumericLiteralNegative) (MulOp UnaryExpression)*
250
+ )*
251
+ }
252
+ MultiplicativeExpression { UnaryExpression (MulOp UnaryExpression)* }
253
+ UnaryExpression { (NotOp | ArithOp) primaryExpression | primaryExpression }
254
+ primaryExpression {
255
+ BrackettedExpression | BuiltInCall | IriOrFunction |
256
+ RDFLiteral | NumericLiteral | BooleanLiteral | Var | ExprTripleTerm
257
+ }
258
+ BrackettedExpression { "(" Expression ")" }
259
+ IriOrFunction { iri ArgList? }
260
+
261
+ // The built-in calls, grouped by arity as the spec's list reads once the
262
+ // parentheses are stripped. Keeping the arity in the grammar means
263
+ // `STRLEN(?a, ?b)` is a parse error rather than something for a later pass.
264
+ BuiltInCall {
265
+ Aggregate |
266
+ FunctionName0 Nil |
267
+ FunctionName1 "(" Expression ")" |
268
+ FunctionName2 "(" Expression "," Expression ")" |
269
+ FunctionName3 "(" Expression "," Expression "," Expression ")" |
270
+ FunctionNameList ExpressionList |
271
+ KwBOUND "(" Var ")" |
272
+ KwBNODE ("(" Expression ")" | Nil) |
273
+ KwSUBSTR "(" Expression "," Expression ("," Expression)? ")" |
274
+ KwREGEX "(" Expression "," Expression ("," Expression)? ")" |
275
+ KwREPLACE "(" Expression "," Expression "," Expression ("," Expression)? ")" |
276
+ ExistsFunc |
277
+ NotExistsFunc
278
+ }
279
+
280
+ FunctionName0 { KwRAND | KwNOW | KwUUID | KwSTRUUID }
281
+
282
+ FunctionName1 {
283
+ KwSTR | KwLANG | KwDATATYPE | KwIRI | KwURI | KwABS | KwCEIL | KwFLOOR | KwROUND |
284
+ KwSTRLEN | KwUCASE | KwLCASE | KwENCODE_FOR_URI | KwYEAR | KwMONTH | KwDAY |
285
+ KwHOURS | KwMINUTES | KwSECONDS | KwTIMEZONE | KwTZ | KwMD5 | KwSHA1 | KwSHA256 |
286
+ KwSHA384 | KwSHA512 | KwISIRI | KwISURI | KwISBLANK | KwISLITERAL | KwISNUMERIC |
287
+ KwISTRIPLE | KwSUBJECT | KwPREDICATE | KwOBJECT | KwLANGDIR | KwHASLANG | KwHASLANGDIR
288
+ }
289
+
290
+ FunctionName2 {
291
+ KwLANGMATCHES | KwCONTAINS | KwSTRSTARTS | KwSTRENDS | KwSTRBEFORE | KwSTRAFTER |
292
+ KwSTRLANG | KwSTRDT | KwSAMETERM
293
+ }
294
+
295
+ FunctionName3 { KwIF | KwSTRLANGDIR | KwTRIPLE }
296
+
297
+ FunctionNameList { KwCONCAT | KwCOALESCE }
298
+
299
+ ExistsFunc { KwEXISTS GroupGraphPattern }
300
+ NotExistsFunc { KwNOT KwEXISTS GroupGraphPattern }
301
+
302
+ Aggregate {
303
+ KwCOUNT "(" KwDISTINCT? ("*" | Expression) ")" |
304
+ (KwSUM | KwMIN | KwMAX | KwAVG | KwSAMPLE) "(" KwDISTINCT? Expression ")" |
305
+ KwGROUP_CONCAT "(" KwDISTINCT? Expression (";" KwSEPARATOR "=" String)? ")"
306
+ }
307
+
308
+ // ---------------------------------------------------------------------- terms
309
+
310
+ RDFLiteral { String (LangDir | Datatype)? }
311
+ Datatype { "^^" iri }
312
+ NumericLiteral { NumericLiteralUnsigned | NumericLiteralPositive | NumericLiteralNegative }
313
+ NumericLiteralUnsigned { Integer | Decimal | Double }
314
+ NumericLiteralPositive { IntegerPositive | DecimalPositive | DoublePositive }
315
+ NumericLiteralNegative { IntegerNegative | DecimalNegative | DoubleNegative }
316
+ BooleanLiteral { KwTRUE | KwFALSE }
317
+ iri { IRIRef | PrefixedName }
318
+ PrefixedName { PNameLN | PNameNS }
319
+ BlankNode { BlankNodeLabel | Anon }
320
+
321
+ // ------------------------------------------------------------------------ SRL
322
+ //
323
+ // SRL: `RULE iri? HeadTemplate 'WHERE' 'DATA'? BodyPattern`, plus ground
324
+ // `DATA` blocks, plus the rule-tuples extension. There is no `IF`/`THEN` and no
325
+ // `FOR`/`IN` clause: both were removed from the grammar upstream
326
+ // (w3c/data-shapes commits 58fdfc6 and cfbcd3c, 2026-08-24).
327
+
328
+ RuleSet { (BaseDecl | PrefixDecl | VersionDecl | Rule | SrlDataBlock)* }
329
+
330
+ Rule { KwRULE iri? HeadTemplate KwWHERE KwDATA? BodyPattern }
331
+
332
+ // A dot-separated list rather than `ConstructTriples | TupleTemplate` repeated:
333
+ // ConstructTriples consumes its own dots, so the two together are ambiguous.
334
+ HeadTemplate { "{" (headItem ("." headItem?)*)? "}" }
335
+ headItem { TupleTemplate | TriplesSameSubject }
336
+
337
+ BodyPattern { "{" srlGroupBody "}" }
338
+ srlGroupBody { TriplesBlock? (srlPatternItem "."? TriplesBlock?)* }
339
+ srlPatternItem { Negation | Filter | Assignment | TuplePattern }
340
+
341
+ Negation { KwNOT KwDATA? BodyPattern }
342
+ Assignment { KwSET "(" Var AssignOp Expression ")" }
343
+
344
+ SrlDataBlock { KwDATA DataTemplate }
345
+ DataTemplate { "{" TriplesTemplate? "}" }
346
+
347
+ TuplePattern { KwTUPLE "(" varOrTerm ("," varOrTerm)* ")" }
348
+ TupleTemplate { KwTUPLE "(" varOrTerm ("," varOrTerm)* ")" }
349
+
350
+ // --------------------------------------------------------------------- tokens
351
+
352
+ @external specialize { Word } keyword from "./keywords" {
353
+ KwBASE, KwPREFIX, KwVERSION,
354
+ KwSELECT, KwDISTINCT, KwREDUCED, KwAS, KwCONSTRUCT, KwWHERE, KwDESCRIBE, KwASK,
355
+ KwFROM, KwNAMED, KwGROUP, KwBY, KwHAVING, KwORDER, KwASC, KwDESC, KwLIMIT,
356
+ KwOFFSET, KwVALUES, KwOPTIONAL, KwGRAPH, KwSERVICE, KwSILENT, KwBIND, KwUNDEF,
357
+ KwMINUS, KwUNION, KwFILTER,
358
+ KwLOAD, KwINTO, KwCLEAR, KwDROP, KwCREATE, KwADD, KwMOVE, KwCOPY, KwTO,
359
+ KwINSERT, KwDELETE, KwDATA, KwWITH, KwUSING, KwDEFAULT, KwALL,
360
+ KwA, KwTRUE, KwFALSE,
361
+ KwSTR, KwLANG, KwLANGMATCHES, KwDATATYPE, KwBOUND, KwIRI, KwURI, KwBNODE,
362
+ KwRAND, KwABS, KwCEIL, KwFLOOR, KwROUND, KwCONCAT, KwSTRLEN, KwUCASE, KwLCASE,
363
+ KwENCODE_FOR_URI, KwCONTAINS, KwSTRSTARTS, KwSTRENDS, KwSTRBEFORE, KwSTRAFTER,
364
+ KwYEAR, KwMONTH, KwDAY, KwHOURS, KwMINUTES, KwSECONDS, KwTIMEZONE, KwTZ,
365
+ KwNOW, KwUUID, KwSTRUUID, KwMD5, KwSHA1, KwSHA256, KwSHA384, KwSHA512,
366
+ KwCOALESCE, KwIF, KwSTRLANG, KwSTRDT, KwSAMETERM, KwISIRI, KwISURI, KwISBLANK,
367
+ KwISLITERAL, KwISNUMERIC, KwREGEX, KwSUBSTR, KwREPLACE, KwEXISTS, KwNOT, KwIN,
368
+ KwCOUNT, KwSUM, KwMIN, KwMAX, KwAVG, KwSAMPLE, KwGROUP_CONCAT, KwSEPARATOR,
369
+ KwTRIPLE, KwISTRIPLE, KwSUBJECT, KwPREDICATE, KwOBJECT,
370
+ KwLANGDIR, KwHASLANG, KwHASLANGDIR, KwSTRLANGDIR,
371
+ KwRULE, KwSET, KwTUPLE
372
+ }
373
+
374
+ @tokens {
375
+ whitespace { $[ \t\r\n]+ }
376
+ Comment { "#" ![\n\r]* }
377
+
378
+ // One token for every bare word; `keywords.ts` turns the ones that are
379
+ // keywords into their own terms, case-insensitively. `-` and `.` are left
380
+ // out so a bare word can never swallow an operator or a statement dot.
381
+ Word { PN_CHARS_BASE $[A-Za-z0-9_]* }
382
+
383
+ IRIRef { "<" (![- <>\"{}|^`\\] | UCHAR)* ">" }
384
+
385
+ PNameNS { PN_PREFIX? ":" }
386
+ PNameLN { PNameNS PN_LOCAL }
387
+
388
+ BlankNodeLabel { "_:" (PN_CHARS_U | $[0-9]) ((PN_CHARS | ".")* PN_CHARS)? }
389
+ Anon { "[" $[ \t\r\n]* "]" }
390
+ Nil { "(" $[ \t\r\n]* ")" }
391
+
392
+ Var1 { "?" VARNAME }
393
+ Var2 { "$" VARNAME }
394
+ VARNAME { (PN_CHARS_U | $[0-9]) (PN_CHARS_U | $[0-9] | $[·] | $[̀-ͯ] | $[‿-⁀])* }
395
+
396
+ LangDir { "@" LANGTAG_PRIMARY ("-" $[a-zA-Z0-9]+)* ("--" ("ltr" | "rtl"))? }
397
+ LANGTAG_PRIMARY {
398
+ $[a-zA-Z] $[a-zA-Z]? $[a-zA-Z]? $[a-zA-Z]? $[a-zA-Z]? $[a-zA-Z]? $[a-zA-Z]? $[a-zA-Z]?
399
+ }
400
+
401
+ Integer { $[0-9]+ }
402
+ Decimal { $[0-9]* "." $[0-9]+ }
403
+ Double { $[0-9]+ "." $[0-9]* EXPONENT | "." $[0-9]+ EXPONENT | $[0-9]+ EXPONENT }
404
+ IntegerPositive { "+" Integer }
405
+ DecimalPositive { "+" Decimal }
406
+ DoublePositive { "+" Double }
407
+ IntegerNegative { "-" Integer }
408
+ DecimalNegative { "-" Decimal }
409
+ DoubleNegative { "-" Double }
410
+ EXPONENT { $[eE] $[+\-]? $[0-9]+ }
411
+
412
+ String {
413
+ "\"" (![\"\\\n\r] | ECHAR | UCHAR)* "\"" |
414
+ "'" (!['\\\n\r] | ECHAR | UCHAR)* "'" |
415
+ "\"\"\"" (![\"\\] | "\\" _ | "\"" ![\"] | "\"\"" ![\"])* "\"\"\"" |
416
+ "'''" (!['\\] | "\\" _ | "'" !['] | "''" !['])* "'''"
417
+ }
418
+ VersionSpecifier {
419
+ "\"" (![\"\\\n\r] | ECHAR | UCHAR)* "\"" |
420
+ "'" (!['\\\n\r] | ECHAR | UCHAR)* "'"
421
+ }
422
+
423
+ ECHAR { "\\" $[tbnrf\"'\\] }
424
+ UCHAR { "\\u" HEX HEX HEX HEX | "\\U" HEX HEX HEX HEX HEX HEX HEX HEX }
425
+ HEX { $[0-9A-Fa-f] }
426
+
427
+ PN_CHARS_BASE {
428
+ $[A-Za-z] |
429
+ $[À-Ö] | $[Ø-ö] | $[ø-˿] |
430
+ $[Ͱ-ͽ] | $[Ϳ-῿] | $[‌-‍] |
431
+ $[⁰-↏] | $[Ⰰ-⿯] | $[、-퟿] |
432
+ $[豈-﷏] | $[ﷰ-�]
433
+ }
434
+ PN_CHARS_U { PN_CHARS_BASE | "_" }
435
+ PN_CHARS { PN_CHARS_U | "-" | $[0-9] | $[·] | $[̀-ͯ] | $[‿-⁀] }
436
+ PN_PREFIX { PN_CHARS_BASE ((PN_CHARS | ".")* PN_CHARS)? }
437
+ PN_LOCAL {
438
+ (PN_CHARS_U | ":" | $[0-9] | PLX) ((PN_CHARS | "." | ":" | PLX)* (PN_CHARS | ":" | PLX))?
439
+ }
440
+ PLX { PERCENT | PN_LOCAL_ESC }
441
+ PERCENT { "%" HEX HEX }
442
+ PN_LOCAL_ESC { "\\" $[_~.!$&'()*+,;=/?#@%\-] }
443
+
444
+ OrOp { "||" }
445
+ AndOp { "&&" }
446
+ CompareOp { "=" | "!=" | "<=" | ">=" | "<" | ">" }
447
+ ArithOp { "+" | "-" }
448
+ MulOp { "*" | "/" }
449
+ NotOp { "!" }
450
+ AssignOp { ":=" }
451
+
452
+ "<<" ">>" "<<(" ")>>" "{|" "|}" "^^" "~" "^" "|" "?"
453
+ "{" "}" "[" "]" "(" ")" ";" "," "." "*" "+" "="
454
+
455
+ // More specific patterns first: Lezer token precedence overrides longest
456
+ // match, so this order spells out "the longer alternative wins".
457
+ //
458
+ // Only genuinely ambiguous pairs are listed. A precedence is a *global*
459
+ // resolution — it beats Lezer's per-state tokenisation — so declaring one
460
+ // between tokens that merely look alike breaks the states where the other
461
+ // one was the only valid choice. `*` is the cautionary tale: with
462
+ // `@precedence { MulOp, "*" }` in place, `SELECT *` lexed its star as
463
+ // multiplication and every `SELECT *` query failed to parse.
464
+ // AssignOp before PNameNS: `:=` must not lex as an empty prefix followed
465
+ // by `=`, which is what SRL's `SET ( ?v := … )` turned into.
466
+ @precedence { PNameLN, AssignOp, PNameNS, Word }
467
+ // A signed literal beats the operator that starts the same way: `?x -1` is an
468
+ // addition whose right operand is `-1`, and `[ :p 1 ]` may have `+1` as its
469
+ // object while `[ :p+ 1 ]` has `+` as a path modifier.
470
+ @precedence { DoublePositive, DecimalPositive, IntegerPositive, DoubleNegative, DecimalNegative, IntegerNegative, ArithOp }
471
+ //
472
+ // The path modifier gets its OWN declaration rather than joining the list
473
+ // above. Listing it after ArithOp would order the two against each other, and
474
+ // a precedence is global: `+` would then lex as arithmetic everywhere,
475
+ // including in `ex:p+/ex:q` where arithmetic is not valid at all. Same trap
476
+ // as `@precedence { MulOp, "*" }` and `SELECT *`.
477
+ @precedence { DoublePositive, DecimalPositive, IntegerPositive, "+" }
478
+ @precedence { Double, Decimal, Integer, "." }
479
+ @precedence { Var1, "?" }
480
+ @precedence { IRIRef, "<<(", "<<" }
481
+ @precedence { ")>>", Nil, ")" }
482
+ @precedence { OrOp, "|" }
483
+ @precedence { Anon, "[" }
484
+ }
485
+
486
+ @detectDelim