sparql_smith/
lib.rs

1use arbitrary::{Arbitrary, Error, Result, Unstructured};
2use std::fmt;
3use std::iter::once;
4use std::ops::ControlFlow;
5
6pub const DATA_TRIG: &str = "
7@prefix : <http://example.org/> .
8@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
9
10:1 :2 :3 , :4 ;
11   :5 true , 1 , '1'^^xsd:decimal , '1'^^xsd:double .
12
13:3 :2 :4 ;
14   :5 false , 0 , '0'^^xsd:decimal , '0'^^xsd:double .
15
16:1 {
17    :1 :2 :3 , 'foo' .
18}
19
20:2 {
21    :3 :2 :1 , false , 'bar'@en .
22}
23
24:3 {
25    :3 :2 :1 , true .
26}
27";
28
29const NUMBER_OF_NAMED_NODES: u8 = 5;
30const NUMBER_OF_VARIABLES: u8 = 4;
31const LITERALS: [&str; 54] = [
32    "\"foo\"",
33    "\"foo\"^^<http://www.w3.org/2001/XMLSchema#string>",
34    "\"foo\"@en",
35    "\"foo\"@en-us",
36    "true",
37    "false",
38    "0",
39    "\"0\"^^<http://www.w3.org/2001/XMLSchema#decimal>",
40    "\"0\"^^<http://www.w3.org/2001/XMLSchema#double>",
41    "\"-0\"^^<http://www.w3.org/2001/XMLSchema#double>",
42    "1",
43    "\"1\"^^<http://www.w3.org/2001/XMLSchema#decimal>",
44    "\"1\"^^<http://www.w3.org/2001/XMLSchema#double>",
45    "-1",
46    "\"-1\"^^<http://www.w3.org/2001/XMLSchema#decimal>",
47    "\"-1\"^^<http://www.w3.org/2001/XMLSchema#double>",
48    "\"INF\"^^<http://www.w3.org/2001/XMLSchema#double>",
49    "\"-INF\"^^<http://www.w3.org/2001/XMLSchema#double>",
50    "\"NaN\"^^<http://www.w3.org/2001/XMLSchema#double>",
51    "\"INF\"^^<http://www.w3.org/2001/XMLSchema#float>",
52    "\"-INF\"^^<http://www.w3.org/2001/XMLSchema#float>",
53    "\"NaN\"^^<http://www.w3.org/2001/XMLSchema#float>",
54    "\"0\"^^<http://www.w3.org/2001/XMLSchema#float>",
55    "\"-0\"^^<http://www.w3.org/2001/XMLSchema#float>",
56    "\"1\"^^<http://www.w3.org/2001/XMLSchema#float>",
57    "\"-1\"^^<http://www.w3.org/2001/XMLSchema#float>",
58    "\"P1YT1S\"^^<http://www.w3.org/2001/XMLSchema#duration>",
59    "\"P1Y\"^^<http://www.w3.org/2001/XMLSchema#duration>",
60    "\"PT1S\"^^<http://www.w3.org/2001/XMLSchema#duration>",
61    "\"P1Y\"^^<http://www.w3.org/2001/XMLSchema#yearMonthDuration>",
62    "\"PT1S\"^^<http://www.w3.org/2001/XMLSchema#dayTimeDuration>",
63    "\"2020-01-01T00:00:00\"^^<http://www.w3.org/2001/XMLSchema#dateTime>",
64    "\"2020-01-01T00:00:00Z\"^^<http://www.w3.org/2001/XMLSchema#dateTime>",
65    "\"2020-01-01T01:00:00.1-14:00\"^^<http://www.w3.org/2001/XMLSchema#dateTime>",
66    "\"2020-01-01T02:00:00.2+14:00\"^^<http://www.w3.org/2001/XMLSchema#dateTime>",
67    "\"2020-01-01T03:00:00.3-10:30\"^^<http://www.w3.org/2001/XMLSchema#dateTime>",
68    "\"2020-01-01T04:00:00.4+10:30\"^^<http://www.w3.org/2001/XMLSchema#dateTime>",
69    "\"2020-01-01\"^^<http://www.w3.org/2001/XMLSchema#date>",
70    "\"2020-01-01Z\"^^<http://www.w3.org/2001/XMLSchema#date>",
71    "\"2020-01-01-14:00\"^^<http://www.w3.org/2001/XMLSchema#date>",
72    "\"2020-01-01+14:00\"^^<http://www.w3.org/2001/XMLSchema#date>",
73    "\"2020-01-01-10:30\"^^<http://www.w3.org/2001/XMLSchema#date>",
74    "\"2020-01-01+10:30\"^^<http://www.w3.org/2001/XMLSchema#date>",
75    "\"00:00:00\"^^<http://www.w3.org/2001/XMLSchema#time>",
76    "\"00:00:00Z\"^^<http://www.w3.org/2001/XMLSchema#time>",
77    "\"01:00:00.1-14:00\"^^<http://www.w3.org/2001/XMLSchema#time>",
78    "\"02:00:00.2+14:00\"^^<http://www.w3.org/2001/XMLSchema#time>",
79    "\"03:00:00.3-10:30\"^^<http://www.w3.org/2001/XMLSchema#time>",
80    "\"04:00:00.4+10:30\"^^<http://www.w3.org/2001/XMLSchema#time>",
81    "\"2020\"^^<http://www.w3.org/2001/XMLSchema#gYear>",
82    "\"2020-01\"^^<http://www.w3.org/2001/XMLSchema#gYearMonth>",
83    "\"--01\"^^<http://www.w3.org/2001/XMLSchema#gMonth>",
84    "\"--01-01\"^^<http://www.w3.org/2001/XMLSchema#gMonthDay>",
85    "\"---01\"^^<http://www.w3.org/2001/XMLSchema#gDay>",
86];
87
88pub struct Query {
89    inner: QueryContent,
90}
91
92#[derive(Arbitrary)]
93struct QueryContent {
94    // [1]  QueryUnit  ::=  Query
95    // [2]  Query      ::=  Prologue ( SelectQuery | ConstructQuery | DescribeQuery | AskQuery ) ValuesClause
96    variant: QueryVariant,
97    values_clause: ValuesClause,
98}
99
100#[expect(clippy::large_enum_variant)]
101#[derive(Arbitrary)]
102enum QueryVariant {
103    Select(SelectQuery),
104    Construct(ConstructQuery),
105    Describe(DescribeQuery),
106    Ask(AskQuery),
107}
108
109impl<'a> Arbitrary<'a> for Query {
110    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
111        Ok(Self {
112            inner: QueryContent::arbitrary(u)?,
113        })
114    }
115
116    fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
117        Ok(Self {
118            inner: QueryContent::arbitrary_take_rest(u)?,
119        })
120    }
121
122    fn size_hint(_depth: usize) -> (usize, Option<usize>) {
123        (20, None)
124    }
125}
126
127impl fmt::Display for Query {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        match &self.inner.variant {
130            QueryVariant::Select(s) => write!(f, "{s}"),
131            QueryVariant::Construct(s) => write!(f, "{s}"),
132            QueryVariant::Describe(s) => write!(f, "{s}"),
133            QueryVariant::Ask(s) => write!(f, "{s}"),
134        }?;
135        write!(f, "{}", self.inner.values_clause)
136    }
137}
138
139impl fmt::Debug for Query {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        fmt::Display::fmt(self, f)
142    }
143}
144
145#[derive(Arbitrary)]
146struct SelectQuery {
147    // [7]   SelectQuery   ::=   SelectClause DatasetClause* WhereClause SolutionModifier
148    select_clause: SelectClause,
149    where_clause: WhereClause,
150    solution_modifier: SolutionModifier,
151}
152
153impl fmt::Display for SelectQuery {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        write!(
156            f,
157            "{}{}{}",
158            self.select_clause, self.where_clause, self.solution_modifier
159        )
160    }
161}
162
163#[derive(Arbitrary)]
164struct SubSelect {
165    // [8]   SubSelect   ::=   SelectClause WhereClause SolutionModifier ValuesClause
166    select_clause: SelectClause,
167    where_clause: WhereClause,
168    solution_modifier: SolutionModifier,
169    values_clause: ValuesClause,
170}
171
172impl fmt::Display for SubSelect {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        write!(
175            f,
176            "{}{}{}{}",
177            self.select_clause, self.where_clause, self.solution_modifier, self.values_clause
178        )
179    }
180}
181
182#[derive(Arbitrary)]
183struct SelectClause {
184    // [9]   SelectClause   ::=   'SELECT' ( 'DISTINCT' | 'REDUCED' )? ( ( Var | ( '(' Expression 'AS' Var ')' ) )+ | '*' )
185    option: Option<SelectOption>,
186    values: SelectValues,
187}
188
189#[derive(Arbitrary)]
190enum SelectOption {
191    Distinct,
192    Reduced,
193}
194
195#[expect(clippy::large_enum_variant)]
196#[derive(Arbitrary)]
197enum SelectValues {
198    Star,
199    Projection {
200        start: SelectProjection,
201        others: Vec<SelectProjection>,
202    },
203}
204
205#[expect(clippy::large_enum_variant)]
206#[derive(Arbitrary)]
207enum SelectProjection {
208    Variable(Var),
209    Projection(Expression, Var),
210}
211
212impl fmt::Display for SelectClause {
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        f.write_str("SELECT")?;
215        if let Some(option) = &self.option {
216            match option {
217                SelectOption::Distinct => f.write_str(" DISTINCT"),
218                SelectOption::Reduced => f.write_str(" REDUCED"),
219            }?;
220        }
221        match &self.values {
222            SelectValues::Star => f.write_str(" *"),
223            SelectValues::Projection { start, others } => {
224                for e in once(start).chain(others) {
225                    match e {
226                        SelectProjection::Variable(v) => write!(f, " {v}"),
227                        SelectProjection::Projection(e, v) => write!(f, " ({e} AS {v})"),
228                    }?;
229                }
230                Ok(())
231            }
232        }
233    }
234}
235
236#[expect(clippy::large_enum_variant)]
237#[derive(Arbitrary)]
238enum ConstructQuery {
239    // [10] ConstructQuery	  ::=  	'CONSTRUCT' ( ConstructTemplate DatasetClause* WhereClause SolutionModifier | DatasetClause* 'WHERE' '{' TriplesTemplate? '}' SolutionModifier )
240    Full {
241        construct_template: ConstructTemplate,
242        where_clause: WhereClause,
243        solution_modifier: SolutionModifier,
244    },
245    Short {
246        triples_template: Option<ConstructTriples>,
247        solution_modifier: SolutionModifier,
248    },
249}
250
251impl fmt::Display for ConstructQuery {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        match self {
254            Self::Full {
255                construct_template,
256                where_clause,
257                solution_modifier,
258            } => write!(
259                f,
260                "CONSTRUCT {construct_template}{where_clause}{solution_modifier}"
261            ),
262            Self::Short {
263                triples_template,
264                solution_modifier,
265            } => {
266                if let Some(triples) = triples_template {
267                    write!(f, "CONSTRUCT WHERE {{ {triples} }}{solution_modifier}")
268                } else {
269                    write!(f, "CONSTRUCT {{}}{solution_modifier}")
270                }
271            }
272        }
273    }
274}
275
276#[derive(Arbitrary)]
277struct DescribeQuery {
278    // [11]  	DescribeQuery	  ::=  	'DESCRIBE' ( VarOrIri+ | '*' ) DatasetClause* WhereClause? SolutionModifier
279    describe: DescribeList,
280    where_clause: WhereClause,
281    solution_modifier: SolutionModifier,
282}
283
284#[derive(Arbitrary)]
285enum DescribeList {
286    Star,
287    Terms {
288        start: VarOrIri,
289        others: Vec<VarOrIri>,
290    },
291}
292
293impl fmt::Display for DescribeQuery {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        f.write_str("DESCRIBE ")?;
296        match &self.describe {
297            DescribeList::Star => f.write_str("*")?,
298            DescribeList::Terms { start, others } => {
299                write!(f, "{start}")?;
300                for e in others {
301                    write!(f, " {e}")?;
302                }
303            }
304        }
305        write!(f, "{}{}", self.where_clause, self.solution_modifier)
306    }
307}
308
309#[derive(Arbitrary)]
310struct AskQuery {
311    // [12]  	AskQuery	  ::=  	'ASK' DatasetClause* WhereClause SolutionModifier
312    where_clause: WhereClause,
313    solution_modifier: SolutionModifier,
314}
315
316impl fmt::Display for AskQuery {
317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318        write!(f, "ASK {}{}", self.where_clause, self.solution_modifier)
319    }
320}
321
322#[derive(Arbitrary)]
323struct WhereClause {
324    // [17]   WhereClause   ::=   'WHERE'? GroupGraphPattern
325    with_where: bool,
326    group_graph_pattern: GroupGraphPattern,
327}
328
329impl fmt::Display for WhereClause {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        if self.with_where {
332            f.write_str(" WHERE ")?;
333        }
334        write!(f, "{}", self.group_graph_pattern)
335    }
336}
337
338#[derive(Arbitrary)]
339struct SolutionModifier {
340    // [18]   SolutionModifier   ::=   GroupClause? HavingClause? OrderClause? LimitOffsetClauses?
341    group: Option<GroupClause>,
342    having: Option<HavingClause>,
343    order: Option<OrderClause>,
344    #[cfg(feature = "limit-offset")]
345    limit_offset: Option<LimitOffsetClauses>,
346}
347
348impl fmt::Display for SolutionModifier {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        if let Some(group) = &self.group {
351            write!(f, " {group}")?;
352        }
353        if let Some(having) = &self.having {
354            write!(f, " {having}")?;
355        }
356        if let Some(order) = &self.order {
357            write!(f, " {order}")?;
358        }
359        #[cfg(feature = "limit-offset")]
360        if let Some(limit_offset) = &self.limit_offset {
361            write!(f, " {limit_offset}")?;
362        }
363        Ok(())
364    }
365}
366
367#[derive(Arbitrary)]
368struct GroupClause {
369    // [19]   GroupClause   ::=   'GROUP' 'BY' GroupCondition+
370    start: GroupCondition,
371    others: Vec<GroupCondition>,
372}
373
374impl fmt::Display for GroupClause {
375    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376        write!(f, "GROUP BY {}", self.start)?;
377        for o in &self.others {
378            write!(f, " {o}")?;
379        }
380        Ok(())
381    }
382}
383
384#[expect(clippy::large_enum_variant)]
385#[derive(Arbitrary)]
386enum GroupCondition {
387    // [20]   GroupCondition   ::=   BuiltInCall | FunctionCall | '(' Expression ( 'AS' Var )? ')' | Var
388    BuiltInCall(BuiltInCall),
389    FunctionCall(FunctionCall),
390    Projection(Expression, Option<Var>),
391    Var(Var),
392}
393
394impl fmt::Display for GroupCondition {
395    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396        match self {
397            Self::BuiltInCall(c) => write!(f, "{c}"),
398            Self::FunctionCall(c) => write!(f, "{c}"),
399            Self::Projection(e, v) => {
400                if let Some(v) = v {
401                    write!(f, "({e} AS {v})")
402                } else {
403                    write!(f, "({e})")
404                }
405            }
406            Self::Var(v) => write!(f, "{v}"),
407        }
408    }
409}
410
411#[derive(Arbitrary)]
412struct HavingClause {
413    // [21]   HavingClause   ::=   'HAVING' HavingCondition+
414    start: HavingCondition,
415    others: Vec<HavingCondition>,
416}
417
418impl fmt::Display for HavingClause {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        write!(f, "HAVING {}", self.start)?;
421        for o in &self.others {
422            write!(f, " {o}")?;
423        }
424        Ok(())
425    }
426}
427
428// [22]   HavingCondition   ::=   Constraint
429type HavingCondition = Constraint;
430
431#[derive(Arbitrary)]
432struct OrderClause {
433    // [23]   OrderClause   ::=   'ORDER' 'BY' OrderCondition+
434    start: OrderCondition,
435    others: Vec<OrderCondition>,
436}
437
438impl fmt::Display for OrderClause {
439    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
440        write!(f, "ORDER BY {}", self.start)?;
441        for other in &self.others {
442            write!(f, "  {other}")?;
443        }
444        Ok(())
445    }
446}
447
448#[expect(clippy::large_enum_variant)]
449#[derive(Arbitrary)]
450enum OrderCondition {
451    // [24]   OrderCondition   ::=   ( ( 'ASC' | 'DESC' ) BrackettedExpression ) | ( Constraint | Var )
452    BrackettedExpression {
453        is_asc: bool,
454        inner: BrackettedExpression,
455    },
456    Constraint(Constraint),
457    Var(Var),
458}
459
460impl fmt::Display for OrderCondition {
461    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
462        match self {
463            Self::BrackettedExpression { is_asc, inner } => {
464                if *is_asc {
465                    write!(f, "ASC{inner}")
466                } else {
467                    write!(f, "DESC{inner}")
468                }
469            }
470            Self::Constraint(c) => write!(f, "{c}"),
471            Self::Var(v) => write!(f, "{v}"),
472        }
473    }
474}
475
476#[cfg(feature = "limit-offset")]
477#[derive(Arbitrary)]
478enum LimitOffsetClauses {
479    // [25]   LimitOffsetClauses   ::=   LimitClause OffsetClause? | OffsetClause LimitClause?
480    LimitOffset(LimitClause, Option<OffsetClause>),
481    OffsetLimit(OffsetClause, Option<LimitClause>),
482}
483
484#[cfg(feature = "limit-offset")]
485impl fmt::Display for LimitOffsetClauses {
486    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487        match self {
488            Self::LimitOffset(l, Some(o)) => write!(f, "{l} {o}"),
489            Self::LimitOffset(l, None) => write!(f, "{l}"),
490            Self::OffsetLimit(o, Some(l)) => write!(f, "{o} {l}"),
491            Self::OffsetLimit(o, None) => write!(f, "{o}"),
492        }
493    }
494}
495
496#[cfg(feature = "limit-offset")]
497#[derive(Arbitrary)]
498struct LimitClause {
499    // [26]   LimitClause   ::=   'LIMIT' INTEGER
500    value: u8,
501}
502
503#[cfg(feature = "limit-offset")]
504impl fmt::Display for LimitClause {
505    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506        write!(f, "LIMIT {}", self.value)
507    }
508}
509
510#[cfg(feature = "limit-offset")]
511#[derive(Arbitrary)]
512struct OffsetClause {
513    // [27]   OffsetClause   ::=   'OFFSET' INTEGER
514    value: u8,
515}
516
517#[cfg(feature = "limit-offset")]
518impl fmt::Display for OffsetClause {
519    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520        write!(f, "OFFSET {}", self.value)
521    }
522}
523
524#[derive(Arbitrary)]
525struct ValuesClause {
526    // [28]   ValuesClause   ::=   ( 'VALUES' DataBlock )?
527    value: Option<DataBlock>,
528}
529
530impl fmt::Display for ValuesClause {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        if let Some(value) = &self.value {
533            write!(f, " VALUES {value}")
534        } else {
535            Ok(())
536        }
537    }
538}
539
540pub struct Update {
541    inner: UpdateContent,
542}
543
544#[derive(Arbitrary)]
545struct UpdateContent {
546    // [3]  UpdateUnit	  ::=  	Update
547    // [29] Update	  ::=  	Prologue ( Update1 ( ';' Update )? )?
548    variants: Vec<Update1>,
549}
550
551impl<'a> Arbitrary<'a> for Update {
552    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
553        Ok(Self {
554            inner: UpdateContent::arbitrary(u)?,
555        })
556    }
557
558    fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
559        Ok(Self {
560            inner: UpdateContent::arbitrary_take_rest(u)?,
561        })
562    }
563
564    fn size_hint(_depth: usize) -> (usize, Option<usize>) {
565        (20, None) // TODO: is it good?
566    }
567}
568
569impl fmt::Display for Update {
570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        for variant in &self.inner.variants {
572            write!(f, "{variant} ; ")?;
573        }
574        Ok(())
575    }
576}
577
578impl fmt::Debug for Update {
579    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
580        fmt::Display::fmt(self, f)
581    }
582}
583
584#[expect(clippy::large_enum_variant)]
585#[derive(Arbitrary)]
586enum Update1 {
587    // [30]  	Update1	  ::=  	Load | Clear | Drop | Add | Move | Copy | Create | InsertData | DeleteData | DeleteWhere | Modify
588    // TODO Load
589    Clear(Clear),
590    Drop(Drop),
591    Add(Add),
592    Move(Move),
593    Copy(Copy),
594    Create(Create),
595    InsertData(InsertData),
596    DeleteData(DeleteData),
597    DeleteWhere(DeleteWhere),
598    Modify(Modify),
599}
600
601impl fmt::Display for Update1 {
602    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
603        match self {
604            Update1::Clear(a) => a.fmt(f),
605            Update1::Drop(a) => a.fmt(f),
606            Update1::Add(a) => a.fmt(f),
607            Update1::Move(a) => a.fmt(f),
608            Update1::Copy(a) => a.fmt(f),
609            Update1::Create(a) => a.fmt(f),
610            Update1::InsertData(a) => a.fmt(f),
611            Update1::DeleteData(a) => a.fmt(f),
612            Update1::DeleteWhere(a) => a.fmt(f),
613            Update1::Modify(a) => a.fmt(f),
614        }
615    }
616}
617
618#[derive(Arbitrary)]
619struct Clear {
620    // [32]  	Clear	  ::=  	'CLEAR' 'SILENT'? GraphRefAll
621    silent: bool,
622    target: GraphRefAll,
623}
624
625impl fmt::Display for Clear {
626    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627        write!(f, "CLEAR ")?;
628        if self.silent {
629            write!(f, "SILENT ")?;
630        }
631        write!(f, "{}", self.target)
632    }
633}
634
635#[derive(Arbitrary)]
636struct Drop {
637    // [33]  	Drop	  ::=  	'DROP' 'SILENT'? GraphRefAll
638    silent: bool,
639    target: GraphRefAll,
640}
641
642impl fmt::Display for Drop {
643    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
644        write!(f, "DROP ")?;
645        if self.silent {
646            write!(f, "SILENT ")?;
647        }
648        write!(f, "{}", self.target)
649    }
650}
651
652#[derive(Arbitrary)]
653struct Create {
654    // [34]  	Create	  ::=  	'CREATE' 'SILENT'? GraphRef
655    silent: bool,
656    target: GraphRef,
657}
658
659impl fmt::Display for Create {
660    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661        write!(f, "CREATE ")?;
662        if self.silent {
663            write!(f, "SILENT ")?;
664        }
665        write!(f, "{}", self.target)
666    }
667}
668
669#[derive(Arbitrary)]
670struct Add {
671    // [35]  	Add	  ::=  	'ADD' 'SILENT'? GraphOrDefault 'TO' GraphOrDefault
672    silent: bool,
673    from: GraphOrDefault,
674    to: GraphOrDefault,
675}
676
677impl fmt::Display for Add {
678    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
679        write!(f, "ADD ")?;
680        if self.silent {
681            write!(f, "SILENT ")?;
682        }
683        write!(f, "{} TO {}", self.from, self.to)
684    }
685}
686
687#[derive(Arbitrary)]
688struct Move {
689    // [36]  	Move	  ::=  	'MOVE' 'SILENT'? GraphOrDefault 'TO' GraphOrDefault
690    silent: bool,
691    from: GraphOrDefault,
692    to: GraphOrDefault,
693}
694
695impl fmt::Display for Move {
696    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
697        write!(f, "MOVE ")?;
698        if self.silent {
699            write!(f, "SILENT ")?;
700        }
701        write!(f, "{} TO {}", self.from, self.to)
702    }
703}
704
705#[derive(Arbitrary)]
706struct Copy {
707    // [37]  	Copy	  ::=  	'COPY' 'SILENT'? GraphOrDefault 'TO' GraphOrDefault
708    silent: bool,
709    from: GraphOrDefault,
710    to: GraphOrDefault,
711}
712
713impl fmt::Display for Copy {
714    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
715        write!(f, "MOVE ")?;
716        if self.silent {
717            write!(f, "SILENT ")?;
718        }
719        write!(f, "{} TO {}", self.from, self.to)
720    }
721}
722
723#[derive(Arbitrary)]
724struct InsertData {
725    // [38]  	InsertData	  ::=  	'INSERT DATA' QuadData
726    data: QuadData,
727}
728
729impl fmt::Display for InsertData {
730    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
731        write!(f, "INSERT DATA {}", self.data)
732    }
733}
734
735#[derive(Arbitrary)]
736struct DeleteData {
737    // [39]  	DeleteData	  ::=  	'DELETE DATA' QuadData
738    data: QuadData,
739}
740
741impl fmt::Display for DeleteData {
742    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743        write!(f, "DELETE DATA {}", self.data)
744    }
745}
746
747#[derive(Arbitrary)]
748struct DeleteWhere {
749    // [40]  	DeleteWhere	  ::=  	'DELETE WHERE' QuadPattern
750    data: QuadPattern,
751}
752
753impl fmt::Display for DeleteWhere {
754    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
755        write!(f, "DELETE WHERE {}", self.data)
756    }
757}
758
759#[derive(Arbitrary)]
760struct Modify {
761    // [41]  	Modify	  ::=  	( 'WITH' iri )? ( DeleteClause InsertClause? | InsertClause ) UsingClause* 'WHERE' GroupGraphPattern
762    // [42]  	DeleteClause	  ::=  	'DELETE' QuadPattern
763    // [43]  	InsertClause	  ::=  	'INSERT' QuadPattern
764    with: Option<Iri>,
765    variant: ModifyVariant,
766    where_: GroupGraphPattern,
767}
768
769#[derive(Arbitrary)]
770enum ModifyVariant {
771    DeleteInsert {
772        delete: QuadPattern,
773        insert: QuadPattern,
774    },
775    Delete(QuadPattern),
776    Insert(QuadPattern),
777}
778
779impl fmt::Display for Modify {
780    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781        if let Some(with) = &self.with {
782            write!(f, "WITH {with} ")?;
783        }
784        match &self.variant {
785            ModifyVariant::DeleteInsert { delete, insert } => write!(
786                f,
787                "DELETE {} INSERT {} WHERE {}",
788                delete, insert, self.where_
789            ),
790            ModifyVariant::Delete(delete) => write!(f, "DELETE {} WHERE {}", delete, self.where_),
791            ModifyVariant::Insert(insert) => write!(f, "INSERT {} WHERE {}", insert, self.where_),
792        }
793    }
794}
795
796#[derive(Arbitrary)]
797enum GraphOrDefault {
798    // [45]  	GraphOrDefault	  ::=  	'DEFAULT' | 'GRAPH'? iri
799    Default,
800    Graph(Iri),
801    Iri(Iri),
802}
803
804impl fmt::Display for GraphOrDefault {
805    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
806        match self {
807            GraphOrDefault::Default => write!(f, "DEFAULT"),
808            GraphOrDefault::Graph(g) => write!(f, "GRAPH {g}"),
809            GraphOrDefault::Iri(g) => g.fmt(f),
810        }
811    }
812}
813
814#[derive(Arbitrary)]
815struct GraphRef {
816    // [46]  	GraphRef	  ::=  	'GRAPH' iri
817    iri: Iri,
818}
819
820impl fmt::Display for GraphRef {
821    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
822        write!(f, "GRAPH {}", self.iri)
823    }
824}
825
826#[derive(Arbitrary)]
827enum GraphRefAll {
828    // [47]  	GraphRefAll	  ::=  	GraphRef | 'DEFAULT' | 'NAMED' | 'ALL'
829    GraphRef(GraphRef),
830    Default,
831    Named,
832    All,
833}
834
835impl fmt::Display for GraphRefAll {
836    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837        match self {
838            GraphRefAll::GraphRef(g) => g.fmt(f),
839            GraphRefAll::Default => write!(f, "DEFAULT"),
840            GraphRefAll::Named => write!(f, "NAMED"),
841            GraphRefAll::All => write!(f, "ALL"),
842        }
843    }
844}
845
846#[derive(Arbitrary)]
847struct QuadPattern {
848    // [48]  	QuadPattern	  ::=  	'{' Quads '}'
849    // [50]  	Quads	  ::=  	TriplesTemplate? ( QuadsNotTriples '.'? TriplesTemplate? )*
850    // TODO: more syntax variations
851    quads: Vec<(VarOrIri, Verb, VarOrIriOrLiteral, Option<VarOrIri>)>,
852}
853
854#[derive(Arbitrary)]
855enum VarOrIriOrLiteral {
856    Iri(Iri),
857    Literal(Literal),
858    Var(Var),
859}
860
861impl fmt::Display for QuadPattern {
862    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
863        f.write_str(" { ")?;
864        for (s, p, o, g) in &self.quads {
865            if let Some(g) = g {
866                write!(f, "GRAPH {g} {{ {s} {p} {o} }} ")?;
867            } else {
868                write!(f, "{s} {p} {o} . ")?;
869            }
870        }
871        f.write_str("}")
872    }
873}
874
875impl fmt::Display for VarOrIriOrLiteral {
876    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
877        match self {
878            VarOrIriOrLiteral::Iri(i) => i.fmt(f),
879            VarOrIriOrLiteral::Literal(l) => l.fmt(f),
880            VarOrIriOrLiteral::Var(v) => v.fmt(f),
881        }
882    }
883}
884
885#[derive(Arbitrary)]
886struct QuadData {
887    // [49]  	QuadData	  ::=  	'{' Quads '}'
888    // [50]  	Quads	  ::=  	TriplesTemplate? ( QuadsNotTriples '.'? TriplesTemplate? )*
889    // TODO: more syntax variations
890    quads: Vec<(Iri, Iri, IriOrLiteral, Option<Iri>)>,
891}
892
893#[derive(Arbitrary)]
894enum IriOrLiteral {
895    Iri(Iri),
896    Literal(Literal),
897}
898
899impl fmt::Display for QuadData {
900    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901        f.write_str(" { ")?;
902        for (s, p, o, g) in &self.quads {
903            if let Some(g) = g {
904                write!(f, "GRAPH {g} {{ {s} {p} {o} }} ")?;
905            } else {
906                write!(f, "{s} {p} {o} . ")?;
907            }
908        }
909        f.write_str("}")
910    }
911}
912
913impl fmt::Display for IriOrLiteral {
914    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
915        match self {
916            IriOrLiteral::Iri(i) => i.fmt(f),
917            IriOrLiteral::Literal(l) => l.fmt(f),
918        }
919    }
920}
921
922#[expect(clippy::large_enum_variant)]
923#[derive(Arbitrary)]
924enum GroupGraphPattern {
925    // [53]   GroupGraphPattern   ::=   '{' ( SubSelect | GroupGraphPatternSub ) '}'
926    GroupGraphPatternSub(GroupGraphPatternSub),
927    SubSelect(Box<SubSelect>),
928}
929
930impl fmt::Display for GroupGraphPattern {
931    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
932        f.write_str(" { ")?;
933        match self {
934            Self::GroupGraphPatternSub(p) => write!(f, "{p}"),
935            Self::SubSelect(s) => write!(f, "{s}"),
936        }?;
937        f.write_str(" } ")
938    }
939}
940
941#[derive(Arbitrary)]
942struct GroupGraphPatternSub {
943    // [54]   GroupGraphPatternSub   ::=   TriplesBlock? ( GraphPatternNotTriples '.'? TriplesBlock? )*
944    start: Option<TriplesBlock>,
945    others: Vec<GroupGraphPatternSubOtherBlock>,
946}
947
948#[derive(Arbitrary)]
949struct GroupGraphPatternSubOtherBlock {
950    start: GraphPatternNotTriples,
951    with_dot: bool,
952    end: Option<TriplesBlock>,
953}
954
955impl fmt::Display for GroupGraphPatternSub {
956    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
957        if let Some(start) = &self.start {
958            write!(f, "{start}")?;
959        }
960        for other in &self.others {
961            write!(f, "{}", other.start)?;
962            if other.with_dot {
963                f.write_str(" . ")?;
964            }
965            if let Some(end) = &other.end {
966                write!(f, "{end}")?;
967            }
968        }
969        Ok(())
970    }
971}
972
973#[derive(Arbitrary)]
974struct TriplesBlock {
975    // [55]   TriplesBlock   ::=   TriplesSameSubjectPath ( '.' TriplesBlock? )?
976    start: TriplesSameSubjectPath,
977    end: Option<Option<Box<TriplesBlock>>>,
978}
979
980impl fmt::Display for TriplesBlock {
981    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
982        write!(f, "{}", self.start)?;
983        if let Some(end) = &self.end {
984            f.write_str(" . ")?;
985            if let Some(end) = end {
986                write!(f, "{end}")?;
987            }
988        }
989        Ok(())
990    }
991}
992
993#[expect(clippy::large_enum_variant)]
994#[derive(Arbitrary)]
995enum GraphPatternNotTriples {
996    // [56]   GraphPatternNotTriples   ::=   GroupOrUnionGraphPattern | OptionalGraphPattern | MinusGraphPattern | GraphGraphPattern | ServiceGraphPattern | Filter | Bind | InlineData
997    GroupOrUnion(GroupOrUnionGraphPattern),
998    Optional(OptionalGraphPattern),
999    Minus(MinusGraphPattern),
1000    Graph(GraphGraphPattern),
1001    Filter(Filter),
1002    Bind(Bind),
1003    InlineData(InlineData),
1004    #[cfg(feature = "service")]
1005    ServiceGraphPattern(ServiceGraphPattern),
1006    #[cfg(feature = "sep-0006")]
1007    Lateral(LateralGraphPattern),
1008}
1009
1010impl fmt::Display for GraphPatternNotTriples {
1011    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012        match self {
1013            Self::GroupOrUnion(p) => write!(f, "{p}"),
1014            Self::Optional(p) => write!(f, "{p}"),
1015            Self::Minus(p) => write!(f, "{p}"),
1016            Self::Graph(p) => write!(f, "{p}"),
1017            Self::Filter(p) => write!(f, "{p}"),
1018            Self::Bind(p) => write!(f, "{p}"),
1019            Self::InlineData(p) => write!(f, "{p}"),
1020            #[cfg(feature = "service")]
1021            Self::ServiceGraphPattern(p) => write!(f, "{p}"),
1022            #[cfg(feature = "sep-0006")]
1023            Self::Lateral(p) => write!(f, "{p}"),
1024        }
1025    }
1026}
1027
1028#[derive(Arbitrary)]
1029struct OptionalGraphPattern {
1030    // [57]   OptionalGraphPattern   ::=   'OPTIONAL' GroupGraphPattern
1031    inner: GroupGraphPattern,
1032}
1033
1034impl fmt::Display for OptionalGraphPattern {
1035    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036        write!(f, " OPTIONAL {}", self.inner)
1037    }
1038}
1039
1040#[cfg(feature = "sep-0006")]
1041#[derive(Arbitrary)]
1042struct LateralGraphPattern {
1043    // []   LateralGraphPattern   ::=   'LATERAL' GroupGraphPattern
1044    inner: GroupGraphPattern,
1045}
1046
1047#[cfg(feature = "sep-0006")]
1048impl fmt::Display for LateralGraphPattern {
1049    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1050        write!(f, " LATERAL {}", self.inner)
1051    }
1052}
1053
1054#[derive(Arbitrary)]
1055struct GraphGraphPattern {
1056    // [58]   GraphGraphPattern   ::=   'GRAPH' VarOrIri GroupGraphPattern
1057    graph: VarOrIri,
1058    inner: GroupGraphPattern,
1059}
1060
1061impl fmt::Display for GraphGraphPattern {
1062    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1063        write!(f, " GRAPH {} {}", self.graph, self.inner)
1064    }
1065}
1066
1067#[cfg(feature = "service")]
1068#[derive(Arbitrary)]
1069struct ServiceGraphPattern {
1070    // [59]  	ServiceGraphPattern	  ::=  	'SERVICE' 'SILENT'? VarOrIri GroupGraphPattern
1071    silent: bool,
1072    #[cfg(feature = "unbound-service")]
1073    service: VarOrIri,
1074    #[cfg(not(feature = "unbound-service"))]
1075    service: Iri,
1076    inner: GroupGraphPattern,
1077}
1078
1079#[cfg(feature = "service")]
1080impl fmt::Display for ServiceGraphPattern {
1081    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1082        write!(f, " SERVICE")?;
1083        if self.silent {
1084            write!(f, " SILENT")?;
1085        }
1086        write!(f, " {} {}", self.service, self.inner)
1087    }
1088}
1089
1090#[derive(Arbitrary)]
1091struct Bind {
1092    // [60]   Bind   ::=   'BIND' '(' Expression 'AS' Var ')'
1093    expression: Expression,
1094    var: Var,
1095}
1096
1097impl fmt::Display for Bind {
1098    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1099        write!(f, " BIND({} AS {})", self.expression, self.var)
1100    }
1101}
1102
1103#[derive(Arbitrary)]
1104struct InlineData {
1105    // [61]   InlineData   ::=   'VALUES' DataBlock
1106    inner: DataBlock,
1107}
1108
1109impl fmt::Display for InlineData {
1110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1111        write!(f, "VALUES {}", self.inner)
1112    }
1113}
1114
1115#[derive(Arbitrary)]
1116enum DataBlock {
1117    // [62]   DataBlock   ::=   InlineDataOneVar | InlineDataFull
1118    OneVar(InlineDataOneVar),
1119    Full(InlineDataFull),
1120}
1121
1122impl fmt::Display for DataBlock {
1123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1124        match self {
1125            Self::OneVar(e) => write!(f, "{e}"),
1126            Self::Full(c) => write!(f, "{c}"),
1127        }
1128    }
1129}
1130
1131#[derive(Arbitrary)]
1132struct InlineDataOneVar {
1133    // [63]   InlineDataOneVar   ::=   Var '{' DataBlockValue* '}'
1134    var: Var,
1135    values: Vec<DataBlockValue>,
1136}
1137
1138impl fmt::Display for InlineDataOneVar {
1139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1140        write!(f, "{} {{", self.var)?;
1141        for v in &self.values {
1142            write!(f, " {v}")?;
1143        }
1144        write!(f, " }}")
1145    }
1146}
1147
1148struct InlineDataFull {
1149    // [64]   InlineDataFull   ::=   ( NIL | '(' Var* ')' ) '{' ( '(' DataBlockValue* ')' | NIL )* '}'
1150    vars: Vec<Var>,
1151    values: Vec<Vec<DataBlockValue>>,
1152}
1153
1154impl<'a> Arbitrary<'a> for InlineDataFull {
1155    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1156        let vars = u.arbitrary_iter()?.collect::<Result<Vec<_>>>()?;
1157
1158        let mut values = Vec::new();
1159        u.arbitrary_loop(Some(0), Some(3), |u| {
1160            let mut row = Vec::with_capacity(vars.len());
1161            u.arbitrary_loop(
1162                Some(vars.len().try_into().map_err(|_| Error::IncorrectFormat)?),
1163                Some(vars.len().try_into().map_err(|_| Error::IncorrectFormat)?),
1164                |u| {
1165                    row.push(u.arbitrary()?);
1166                    Ok(ControlFlow::Continue(()))
1167                },
1168            )?;
1169            values.push(row);
1170            Ok(ControlFlow::Continue(()))
1171        })?;
1172
1173        Ok(Self { vars, values })
1174    }
1175}
1176
1177impl fmt::Display for InlineDataFull {
1178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1179        f.write_str("( ")?;
1180        for v in &self.vars {
1181            write!(f, " {v}")?;
1182        }
1183        f.write_str(" ) {")?;
1184        for vs in &self.values {
1185            f.write_str(" (")?;
1186            for v in vs {
1187                write!(f, " {v}")?;
1188            }
1189            f.write_str(" )")?;
1190        }
1191        f.write_str(" }")
1192    }
1193}
1194
1195#[derive(Arbitrary)]
1196enum DataBlockValue {
1197    // [65]   DataBlockValue   ::=   iri | RDFLiteral | NumericLiteral | BooleanLiteral | 'UNDEF'
1198    Iri(Iri),
1199    Literal(Literal),
1200    Undef,
1201}
1202
1203impl fmt::Display for DataBlockValue {
1204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1205        match self {
1206            Self::Iri(i) => write!(f, "{i}"),
1207            Self::Literal(l) => write!(f, "{l}"),
1208            Self::Undef => f.write_str("UNDEF"),
1209        }
1210    }
1211}
1212
1213#[derive(Arbitrary)]
1214struct MinusGraphPattern {
1215    // [66]   MinusGraphPattern   ::=   'MINUS' GroupGraphPattern
1216    inner: GroupGraphPattern,
1217}
1218
1219impl fmt::Display for MinusGraphPattern {
1220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1221        write!(f, " MINUS {}", self.inner)
1222    }
1223}
1224
1225#[derive(Arbitrary)]
1226struct GroupOrUnionGraphPattern {
1227    // [67]   GroupOrUnionGraphPattern   ::=   GroupGraphPattern ( 'UNION' GroupGraphPattern )*
1228    start: GroupGraphPattern,
1229    others: Vec<GroupGraphPattern>,
1230}
1231
1232impl fmt::Display for GroupOrUnionGraphPattern {
1233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1234        write!(f, "{}", self.start)?;
1235        for other in &self.others {
1236            write!(f, " UNION {other}")?;
1237        }
1238        Ok(())
1239    }
1240}
1241
1242#[derive(Arbitrary)]
1243struct Filter {
1244    // [68]   Filter   ::=   'FILTER' Constraint
1245    constraint: Constraint,
1246}
1247
1248impl fmt::Display for Filter {
1249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250        write!(f, "FILTER {}", self.constraint)
1251    }
1252}
1253
1254#[expect(clippy::large_enum_variant)]
1255#[derive(Arbitrary)]
1256enum Constraint {
1257    // [69]   Constraint   ::=   BrackettedExpression | BuiltInCall | FunctionCall
1258    BrackettedExpression(BrackettedExpression),
1259    BuiltInCall(BuiltInCall),
1260    FunctionCall(FunctionCall),
1261}
1262
1263impl fmt::Display for Constraint {
1264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1265        match self {
1266            Self::BrackettedExpression(e) => write!(f, "{e}"),
1267            Self::BuiltInCall(c) => write!(f, "{c}"),
1268            Self::FunctionCall(c) => write!(f, "{c}"),
1269        }
1270    }
1271}
1272
1273#[derive(Arbitrary)]
1274struct FunctionCall {
1275    // [70]   FunctionCall   ::=   iri ArgList
1276    iri: FunctionCallName,
1277    args: ArgList,
1278}
1279
1280impl fmt::Display for FunctionCall {
1281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1282        write!(f, "{}{}", self.iri, self.args)
1283    }
1284}
1285
1286#[derive(Arbitrary)]
1287#[expect(clippy::enum_variant_names)]
1288enum FunctionCallName {
1289    XsdString,
1290    XsdInteger,
1291    XsdDecimal,
1292    XsdDouble,
1293    XsdBoolean,
1294    XsdDateTime,
1295    XsdDate,
1296    XsdTime,
1297    XsdDuration,
1298    XsdYearMonthDuration,
1299    XsdDayTimeDuration,
1300    XsdGYear,
1301    XsdGMonth,
1302    XsdGDay,
1303    XsdGYearMonth,
1304    XsdGMonthDay,
1305}
1306
1307impl fmt::Display for FunctionCallName {
1308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1309        f.write_str(match self {
1310            FunctionCallName::XsdString => "<http://www.w3.org/2001/XMLSchema#string>",
1311            FunctionCallName::XsdInteger => "<http://www.w3.org/2001/XMLSchema#integer>",
1312            FunctionCallName::XsdDecimal => "<http://www.w3.org/2001/XMLSchema#decimal>",
1313            FunctionCallName::XsdDouble => "<http://www.w3.org/2001/XMLSchema#double>",
1314            FunctionCallName::XsdBoolean => "<http://www.w3.org/2001/XMLSchema#boolean>",
1315            FunctionCallName::XsdDateTime => "<http://www.w3.org/2001/XMLSchema#dateTime>",
1316            FunctionCallName::XsdDate => "<http://www.w3.org/2001/XMLSchema#date>",
1317            FunctionCallName::XsdTime => "<http://www.w3.org/2001/XMLSchema#time>",
1318            FunctionCallName::XsdDuration => "<http://www.w3.org/2001/XMLSchema#duration>",
1319            FunctionCallName::XsdYearMonthDuration => {
1320                "<http://www.w3.org/2001/XMLSchema#yearMonthDuration>"
1321            }
1322            FunctionCallName::XsdDayTimeDuration => {
1323                "<http://www.w3.org/2001/XMLSchema#dayTimeDuration>"
1324            }
1325            FunctionCallName::XsdGYear => "<http://www.w3.org/2001/XMLSchema#gYear>",
1326            FunctionCallName::XsdGMonth => "<http://www.w3.org/2001/XMLSchema#gMonth>",
1327            FunctionCallName::XsdGDay => "<http://www.w3.org/2001/XMLSchema#gDay>",
1328            FunctionCallName::XsdGYearMonth => "<http://www.w3.org/2001/XMLSchema#gYearMonth>",
1329            FunctionCallName::XsdGMonthDay => "<http://www.w3.org/2001/XMLSchema#gMonthDay>",
1330        })
1331    }
1332}
1333
1334#[derive(Arbitrary)]
1335enum ArgList {
1336    // [71]   ArgList   ::=   NIL | '(' 'DISTINCT'? Expression ( ',' Expression )* ')'
1337    Nil,
1338    NotNil {
1339        // TODO: DISTINCT
1340        start: Box<Expression>,
1341        others: Vec<Expression>,
1342    },
1343}
1344
1345impl fmt::Display for ArgList {
1346    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1347        f.write_str("(")?;
1348        if let Self::NotNil { start, others } = self {
1349            write!(f, "{start}")?;
1350            for e in others {
1351                write!(f, ", {e}")?;
1352            }
1353        }
1354        f.write_str(")")
1355    }
1356}
1357
1358#[derive(Arbitrary)]
1359struct ExpressionList {
1360    // [72]   ExpressionList   ::=   NIL | '(' Expression ( ',' Expression )* ')'
1361    inner: Vec<Expression>,
1362}
1363
1364impl fmt::Display for ExpressionList {
1365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1366        f.write_str("(")?;
1367        for (i, e) in self.inner.iter().enumerate() {
1368            if i > 0 {
1369                f.write_str(", ")?;
1370            }
1371            write!(f, "{e}")?;
1372        }
1373        f.write_str(")")
1374    }
1375}
1376
1377#[derive(Arbitrary)]
1378struct ConstructTemplate {
1379    // [73]  	ConstructTemplate	  ::=  	'{' ConstructTriples? '}'
1380    triples: Option<ConstructTriples>,
1381}
1382
1383impl fmt::Display for ConstructTemplate {
1384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1385        if let Some(triples) = &self.triples {
1386            write!(f, "{{ {triples} }}")
1387        } else {
1388            f.write_str("{}")
1389        }
1390    }
1391}
1392
1393#[derive(Arbitrary)]
1394struct ConstructTriples {
1395    // [74]  	ConstructTriples	  ::=  	TriplesSameSubject ( '.' ConstructTriples? )?
1396    start: TriplesSameSubject,
1397    others: Vec<TriplesSameSubject>,
1398}
1399
1400impl fmt::Display for ConstructTriples {
1401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1402        write!(f, "{}", self.start)?;
1403        for other in &self.others {
1404            write!(f, " . {other}")?;
1405        }
1406        Ok(())
1407    }
1408}
1409
1410#[derive(Arbitrary)]
1411enum TriplesSameSubject {
1412    // [75]  	TriplesSameSubject	  ::=  	VarOrTerm PropertyListNotEmpty | TriplesNode PropertyList
1413    Atomic {
1414        subject: VarOrTerm,
1415        predicate_object: PropertyListNotEmpty,
1416    },
1417    Other {
1418        subject: TriplesNode,
1419        predicate_object: PropertyList,
1420    },
1421}
1422
1423impl fmt::Display for TriplesSameSubject {
1424    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1425        match self {
1426            Self::Atomic {
1427                subject,
1428                predicate_object,
1429            } => {
1430                write!(f, "{subject}{predicate_object}")
1431            }
1432            Self::Other {
1433                subject,
1434                predicate_object,
1435            } => {
1436                write!(f, "{subject} {predicate_object}")
1437            }
1438        }
1439    }
1440}
1441
1442#[derive(Arbitrary)]
1443struct PropertyList {
1444    // [76]  	PropertyList	  ::=  	PropertyListNotEmpty?
1445    inner: Option<PropertyListNotEmpty>,
1446}
1447
1448impl fmt::Display for PropertyList {
1449    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1450        if let Some(p) = &self.inner {
1451            write!(f, "{p}")
1452        } else {
1453            Ok(())
1454        }
1455    }
1456}
1457
1458#[derive(Arbitrary)]
1459struct PropertyListNotEmpty {
1460    // [77]   PropertyListNotEmpty   ::=   Verb ObjectList ( ';' ( Verb ObjectList )? )*
1461    start_predicate: Verb,
1462    start_object: Box<ObjectList>,
1463    others: Vec<Option<PropertyListElement>>,
1464}
1465
1466#[derive(Arbitrary)]
1467struct PropertyListElement {
1468    predicate: Verb,
1469    object: ObjectList,
1470}
1471
1472impl fmt::Display for PropertyListNotEmpty {
1473    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1474        write!(f, "{} {}", self.start_predicate, self.start_object)?;
1475        for other in &self.others {
1476            f.write_str(" ; ")?;
1477            if let Some(e) = other {
1478                write!(f, "{} {}", e.predicate, e.object)?;
1479            }
1480        }
1481        Ok(())
1482    }
1483}
1484
1485#[derive(Arbitrary)]
1486enum Verb {
1487    // [78]   Verb   ::=   VarOrIri | 'a'
1488    VarOrIri(VarOrIri),
1489    A,
1490}
1491
1492impl fmt::Display for Verb {
1493    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1494        match self {
1495            Self::VarOrIri(iri) => write!(f, "{iri}"),
1496            Self::A => f.write_str(" a "),
1497        }
1498    }
1499}
1500
1501#[derive(Arbitrary)]
1502struct ObjectList {
1503    // [79]   ObjectList   ::=   Object ( ',' Object )*
1504    start: Object,
1505    others: Vec<Object>,
1506}
1507
1508impl fmt::Display for ObjectList {
1509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1510        write!(f, "{}", self.start)?;
1511        for other in &self.others {
1512            f.write_str(" , ")?;
1513            write!(f, "{other}")?;
1514        }
1515        Ok(())
1516    }
1517}
1518
1519// [80]   Object   ::=   GraphNode
1520type Object = GraphNode;
1521
1522#[derive(Arbitrary)]
1523enum TriplesSameSubjectPath {
1524    // [81]   TriplesSameSubjectPath   ::=   VarOrTerm PropertyListPathNotEmpty | TriplesNodePath PropertyListPath
1525    Atomic {
1526        subject: VarOrTerm,
1527        predicate_object: PropertyListPathNotEmpty,
1528    },
1529    Other {
1530        subject: TriplesNodePath,
1531        predicate_object: PropertyListPath,
1532    },
1533}
1534
1535impl fmt::Display for TriplesSameSubjectPath {
1536    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1537        match self {
1538            Self::Atomic {
1539                subject,
1540                predicate_object,
1541            } => {
1542                write!(f, "{subject}{predicate_object}")
1543            }
1544            Self::Other {
1545                subject,
1546                predicate_object,
1547            } => {
1548                write!(f, "{subject} {predicate_object}")
1549            }
1550        }
1551    }
1552}
1553
1554#[derive(Arbitrary)]
1555struct PropertyListPath {
1556    // [82]   PropertyListPath   ::=   PropertyListPathNotEmpty?
1557    inner: Option<PropertyListPathNotEmpty>,
1558}
1559
1560impl fmt::Display for PropertyListPath {
1561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1562        if let Some(p) = &self.inner {
1563            write!(f, "{p}")
1564        } else {
1565            Ok(())
1566        }
1567    }
1568}
1569
1570#[derive(Arbitrary)]
1571struct PropertyListPathNotEmpty {
1572    // [83]   PropertyListPathNotEmpty   ::=   ( VerbPath | VerbSimple ) ObjectListPath ( ';' ( ( VerbPath | VerbSimple ) ObjectListPath )? )*
1573    start_predicate: PropertyListPathNotEmptyVerb,
1574    start_object: Box<ObjectListPath>,
1575    others: Vec<Option<PropertyListPathElement>>,
1576}
1577
1578#[derive(Arbitrary)]
1579enum PropertyListPathNotEmptyVerb {
1580    VerbPath(VerbPath),
1581    VerbSimple(VerbSimple),
1582}
1583
1584#[derive(Arbitrary)]
1585struct PropertyListPathElement {
1586    predicate: PropertyListPathNotEmptyVerb,
1587    object: ObjectListPath,
1588}
1589
1590impl fmt::Display for PropertyListPathNotEmpty {
1591    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1592        match &self.start_predicate {
1593            PropertyListPathNotEmptyVerb::VerbPath(p) => write!(f, "{p}"),
1594            PropertyListPathNotEmptyVerb::VerbSimple(s) => write!(f, "{s}"),
1595        }?;
1596        write!(f, "{}", self.start_object)?;
1597        for other in &self.others {
1598            f.write_str(" ; ")?;
1599            if let Some(e) = other {
1600                match &e.predicate {
1601                    PropertyListPathNotEmptyVerb::VerbPath(p) => write!(f, "{p}"),
1602                    PropertyListPathNotEmptyVerb::VerbSimple(s) => write!(f, "{s}"),
1603                }?;
1604                write!(f, "{}", e.object)?;
1605            }
1606        }
1607        Ok(())
1608    }
1609}
1610
1611// [84]   VerbPath   ::=   Path
1612type VerbPath = Path;
1613
1614// [85]   VerbSimple   ::=   Var
1615type VerbSimple = Var;
1616
1617#[derive(Arbitrary)]
1618struct ObjectListPath {
1619    // [86]   ObjectListPath   ::=   ObjectPath ( ',' ObjectPath )*
1620    start: ObjectPath,
1621    others: Vec<ObjectPath>,
1622}
1623
1624impl fmt::Display for ObjectListPath {
1625    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1626        write!(f, "{}", self.start)?;
1627        for other in &self.others {
1628            write!(f, " , {other}")?;
1629        }
1630        Ok(())
1631    }
1632}
1633
1634// [87]   ObjectPath   ::=   GraphNodePath
1635type ObjectPath = GraphNodePath;
1636
1637// [88]   Path   ::=   PathAlternative
1638type Path = PathAlternative;
1639
1640#[derive(Arbitrary)]
1641struct PathAlternative {
1642    // [89]   PathAlternative   ::=   PathSequence ( '|' PathSequence )*
1643    start: PathSequence,
1644    others: Vec<PathSequence>,
1645}
1646
1647impl fmt::Display for PathAlternative {
1648    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1649        write!(f, "{}", self.start)?;
1650        for other in &self.others {
1651            write!(f, " | {other}")?;
1652        }
1653        Ok(())
1654    }
1655}
1656
1657#[derive(Arbitrary)]
1658struct PathSequence {
1659    // [90]   PathSequence   ::=   PathEltOrInverse ( '/' PathEltOrInverse )*
1660    start: PathEltOrInverse,
1661    others: Vec<PathEltOrInverse>,
1662}
1663
1664impl fmt::Display for PathSequence {
1665    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1666        write!(f, "{}", self.start)?;
1667        for other in &self.others {
1668            write!(f, " / {other}")?;
1669        }
1670        Ok(())
1671    }
1672}
1673
1674#[derive(Arbitrary)]
1675struct PathElt {
1676    // [91]   PathElt   ::=   PathPrimary PathMod?
1677    path: PathPrimary,
1678    mode: Option<PathMod>,
1679}
1680
1681impl fmt::Display for PathElt {
1682    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1683        write!(f, "{}", self.path)?;
1684        if let Some(mode) = &self.mode {
1685            write!(f, "{mode}")?;
1686        }
1687        Ok(())
1688    }
1689}
1690
1691#[derive(Arbitrary)]
1692enum PathEltOrInverse {
1693    // [92]   PathEltOrInverse   ::=   PathElt | '^' PathElt
1694    PathElt(PathElt),
1695    Inverse(PathElt),
1696}
1697
1698impl fmt::Display for PathEltOrInverse {
1699    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1700        match self {
1701            Self::PathElt(e) => write!(f, "{e}"),
1702            Self::Inverse(e) => write!(f, " ^{e}"),
1703        }
1704    }
1705}
1706
1707#[derive(Arbitrary)]
1708enum PathMod {
1709    // [93]   PathMod   ::=   '?' | '*' | '+'
1710    ZeroOrOne,
1711    ZeroOrMore,
1712    OneOrMore,
1713}
1714
1715impl fmt::Display for PathMod {
1716    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1717        match self {
1718            Self::ZeroOrOne => f.write_str(" ? "),
1719            Self::ZeroOrMore => f.write_str(" * "),
1720            Self::OneOrMore => f.write_str(" + "),
1721        }
1722    }
1723}
1724
1725#[derive(Arbitrary)]
1726enum PathPrimary {
1727    // [94]   PathPrimary   ::=   iri | 'a' | '!' PathNegatedPropertySet | '(' Path ')'
1728    Iri(Iri),
1729    A,
1730    Negated(PathNegatedPropertySet),
1731    Child(Box<Path>),
1732}
1733
1734impl fmt::Display for PathPrimary {
1735    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1736        match self {
1737            Self::Iri(iri) => write!(f, "{iri}"),
1738            Self::A => f.write_str(" a "),
1739            Self::Negated(n) => write!(f, "!{n}"),
1740            Self::Child(c) => write!(f, "({c})"),
1741        }
1742    }
1743}
1744
1745#[derive(Arbitrary)]
1746enum PathNegatedPropertySet {
1747    // [95]   PathNegatedPropertySet   ::=   PathOneInPropertySet | '(' ( PathOneInPropertySet ( '|' PathOneInPropertySet )* )? ')'
1748    Single(PathOneInPropertySet),
1749    Multiple {
1750        start: PathOneInPropertySet,
1751        others: Vec<PathOneInPropertySet>,
1752    },
1753}
1754
1755impl fmt::Display for PathNegatedPropertySet {
1756    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1757        match self {
1758            Self::Single(p) => write!(f, "{p}"),
1759            Self::Multiple { start, others } => {
1760                write!(f, " ( {start}")?;
1761                for other in others {
1762                    write!(f, " | {other}")?;
1763                }
1764                f.write_str(" ) ")
1765            }
1766        }
1767    }
1768}
1769
1770#[derive(Arbitrary)]
1771enum PathOneInPropertySet {
1772    // [96]   PathOneInPropertySet   ::=   iri | 'a' | '^' ( iri | 'a' )
1773    Iri(Iri),
1774    A,
1775    NegatedIri(Iri),
1776    NegatedA,
1777}
1778
1779impl fmt::Display for PathOneInPropertySet {
1780    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1781        match self {
1782            Self::Iri(iri) => write!(f, "{iri}"),
1783            Self::A => f.write_str(" a "),
1784            Self::NegatedIri(iri) => write!(f, "^{iri}"),
1785            Self::NegatedA => f.write_str(" ^a "),
1786        }
1787    }
1788}
1789
1790#[derive(Arbitrary)]
1791enum TriplesNode {
1792    // [98]   TriplesNode   ::=   Collection | BlankNodePropertyList
1793    Collection(Collection),
1794    BlankNodePropertyList(BlankNodePropertyList),
1795}
1796
1797impl fmt::Display for TriplesNode {
1798    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1799        match self {
1800            Self::Collection(p) => write!(f, "{p}"),
1801            Self::BlankNodePropertyList(p) => write!(f, "{p}"),
1802        }
1803    }
1804}
1805
1806#[derive(Arbitrary)]
1807struct BlankNodePropertyList {
1808    // [99]   BlankNodePropertyList   ::=   '[' PropertyListNotEmpty ']'
1809    inner: PropertyListNotEmpty,
1810}
1811
1812impl fmt::Display for BlankNodePropertyList {
1813    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1814        write!(f, "[ {} ]", self.inner)
1815    }
1816}
1817
1818#[derive(Arbitrary)]
1819enum TriplesNodePath {
1820    // [100]   TriplesNodePath   ::=   CollectionPath | BlankNodePropertyListPath
1821    CollectionPath(CollectionPath),
1822    BlankNodePropertyListPath(BlankNodePropertyListPath),
1823}
1824
1825impl fmt::Display for TriplesNodePath {
1826    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1827        match self {
1828            Self::CollectionPath(p) => write!(f, "{p}"),
1829            Self::BlankNodePropertyListPath(p) => write!(f, "{p}"),
1830        }
1831    }
1832}
1833
1834#[derive(Arbitrary)]
1835struct BlankNodePropertyListPath {
1836    // [101]   BlankNodePropertyListPath   ::=   '[' PropertyListPathNotEmpty ']'
1837    inner: PropertyListPathNotEmpty,
1838}
1839
1840impl fmt::Display for BlankNodePropertyListPath {
1841    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1842        write!(f, "[ {} ]", self.inner)
1843    }
1844}
1845
1846#[derive(Arbitrary)]
1847struct Collection {
1848    // [102]   Collection   ::=   '(' GraphNode+ ')'
1849    start: Box<GraphNode>,
1850    others: Vec<GraphNode>,
1851}
1852
1853impl fmt::Display for Collection {
1854    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1855        write!(f, "( {}", self.start)?;
1856        for e in &self.others {
1857            write!(f, " {e}")?;
1858        }
1859        f.write_str(" )")
1860    }
1861}
1862
1863#[derive(Arbitrary)]
1864struct CollectionPath {
1865    // [103]   CollectionPath   ::=   '(' GraphNodePath+ ')'
1866    start: Box<GraphNodePath>,
1867    others: Vec<GraphNodePath>,
1868}
1869
1870impl fmt::Display for CollectionPath {
1871    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1872        write!(f, "( {}", self.start)?;
1873        for e in &self.others {
1874            write!(f, " {e}")?;
1875        }
1876        f.write_str(" )")
1877    }
1878}
1879
1880#[derive(Arbitrary)]
1881enum GraphNode {
1882    // [104]   GraphNode   ::=   VarOrTerm | TriplesNode
1883    VarOrTerm(VarOrTerm),
1884    TriplesNode(TriplesNode),
1885}
1886
1887impl fmt::Display for GraphNode {
1888    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1889        match self {
1890            Self::VarOrTerm(t) => write!(f, "{t}"),
1891            Self::TriplesNode(t) => write!(f, "{t}"),
1892        }
1893    }
1894}
1895
1896#[derive(Arbitrary)]
1897enum GraphNodePath {
1898    // [105]   GraphNodePath   ::=   VarOrTerm | TriplesNodePath
1899    VarOrTerm(VarOrTerm),
1900    TriplesNodePath(TriplesNodePath),
1901}
1902
1903impl fmt::Display for GraphNodePath {
1904    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1905        match self {
1906            Self::VarOrTerm(t) => write!(f, "{t}"),
1907            Self::TriplesNodePath(p) => write!(f, "{p}"),
1908        }
1909    }
1910}
1911
1912#[derive(Arbitrary)]
1913enum VarOrTerm {
1914    // [106]   VarOrTerm   ::=   Var | GraphTerm
1915    Var(Var),
1916    GraphTerm(GraphTerm),
1917}
1918
1919impl fmt::Display for VarOrTerm {
1920    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1921        match self {
1922            Self::Var(v) => write!(f, "{v}"),
1923            Self::GraphTerm(t) => write!(f, "{t}"),
1924        }
1925    }
1926}
1927
1928#[derive(Arbitrary)]
1929enum VarOrIri {
1930    // [107]   VarOrIri   ::=   Var | iri
1931    Var(Var),
1932    Iri(Iri),
1933}
1934
1935impl fmt::Display for VarOrIri {
1936    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1937        match self {
1938            Self::Var(v) => write!(f, "{v}"),
1939            Self::Iri(t) => write!(f, "{t}"),
1940        }
1941    }
1942}
1943
1944struct Var {
1945    // [108]   Var   ::=   VAR1 | VAR2
1946    value: u8,
1947}
1948
1949impl Arbitrary<'_> for Var {
1950    fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> {
1951        Ok(Self {
1952            value: u.int_in_range(1..=NUMBER_OF_VARIABLES)?,
1953        })
1954    }
1955
1956    fn size_hint(depth: usize) -> (usize, Option<usize>) {
1957        <u8 as Arbitrary>::size_hint(depth)
1958    }
1959}
1960
1961impl fmt::Display for Var {
1962    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1963        write!(f, " ?{} ", self.value)
1964    }
1965}
1966
1967#[derive(Arbitrary)]
1968enum GraphTerm {
1969    // [109]   GraphTerm   ::=   iri | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | NIL
1970    Iri(Iri),
1971    Literal(Literal),
1972    Nil,
1973    // TODO: BlankNode
1974}
1975
1976impl fmt::Display for GraphTerm {
1977    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1978        match self {
1979            Self::Iri(iri) => write!(f, "{iri}"),
1980            Self::Literal(l) => write!(f, "{l}"),
1981            Self::Nil => f.write_str(" () "),
1982        }
1983    }
1984}
1985
1986// [110]   Expression   ::=   ConditionalOrExpression
1987type Expression = ConditionalOrExpression;
1988
1989#[derive(Arbitrary)]
1990struct ConditionalOrExpression {
1991    // [111]   ConditionalOrExpression   ::=   ConditionalAndExpression ( '||' ConditionalAndExpression )*
1992    start: ConditionalAndExpression,
1993    others: Vec<ConditionalAndExpression>,
1994}
1995
1996impl fmt::Display for ConditionalOrExpression {
1997    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1998        write!(f, "{}", self.start)?;
1999        for e in &self.others {
2000            write!(f, " || {e}")?;
2001        }
2002        Ok(())
2003    }
2004}
2005
2006#[derive(Arbitrary)]
2007struct ConditionalAndExpression {
2008    // [112]   ConditionalAndExpression   ::=   ValueLogical ( '&&' ValueLogical )*
2009    start: ValueLogical,
2010    others: Vec<ValueLogical>,
2011}
2012
2013impl fmt::Display for ConditionalAndExpression {
2014    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2015        write!(f, "{}", self.start)?;
2016        for e in &self.others {
2017            write!(f, " && {e}")?;
2018        }
2019        Ok(())
2020    }
2021}
2022
2023// [113]   ValueLogical   ::=   RelationalExpression
2024type ValueLogical = RelationalExpression;
2025
2026#[derive(Arbitrary)]
2027enum RelationalExpression {
2028    // [114]   RelationalExpression   ::=   NumericExpression ( '=' NumericExpression | '!=' NumericExpression | '<' NumericExpression | '>' NumericExpression | '<=' NumericExpression | '>=' NumericExpression | 'IN' ExpressionList | 'NOT' 'IN' ExpressionList )?
2029    Base(NumericExpression),
2030    Equal(NumericExpression, NumericExpression),
2031    NotEqual(NumericExpression, NumericExpression),
2032    Less(NumericExpression, NumericExpression),
2033    LessOrEqual(NumericExpression, NumericExpression),
2034    Greater(NumericExpression, NumericExpression),
2035    GreaterOrEqual(NumericExpression, NumericExpression),
2036    In(NumericExpression, ExpressionList),
2037    NotIn(NumericExpression, ExpressionList),
2038}
2039
2040impl fmt::Display for RelationalExpression {
2041    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2042        match self {
2043            Self::Base(e) => write!(f, "{e}"),
2044            Self::Equal(a, b) => write!(f, "{a} = {b}"),
2045            Self::NotEqual(a, b) => write!(f, "{a} != {b}"),
2046            Self::Less(a, b) => write!(f, "{a} < {b}"),
2047            Self::LessOrEqual(a, b) => write!(f, "{a} <= {b}"),
2048            Self::Greater(a, b) => write!(f, "{a} > {b}"),
2049            Self::GreaterOrEqual(a, b) => write!(f, "{a} >= {b}"),
2050            Self::In(a, b) => write!(f, "{a} IN {b}"),
2051            Self::NotIn(a, b) => write!(f, "{a} NOT IN {b}"),
2052        }
2053    }
2054}
2055
2056// [115]   NumericExpression   ::=   AdditiveExpression
2057type NumericExpression = AdditiveExpression;
2058
2059#[derive(Arbitrary)]
2060struct AdditiveExpression {
2061    // [116]   AdditiveExpression   ::=   MultiplicativeExpression ( '+' MultiplicativeExpression | '-' MultiplicativeExpression | ( NumericLiteralPositive | NumericLiteralNegative ) ( ( '*' UnaryExpression ) | ( '/' UnaryExpression ) )* )*
2062    base: MultiplicativeExpression,
2063    elements: Vec<AdditiveExpressionElements>,
2064}
2065
2066#[derive(Arbitrary)]
2067enum AdditiveExpressionElements {
2068    Plus(MultiplicativeExpression),
2069    Minus(MultiplicativeExpression),
2070    // NumericLiteralPositive | NumericLiteralNegative are already covered by UnaryExpression, we don't need to disambiguate
2071}
2072
2073impl fmt::Display for AdditiveExpression {
2074    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2075        write!(f, "{}", self.base)?;
2076        for element in &self.elements {
2077            match element {
2078                AdditiveExpressionElements::Plus(e) => write!(f, " + {e}"),
2079                AdditiveExpressionElements::Minus(e) => write!(f, " - {e}"),
2080            }?;
2081        }
2082        Ok(())
2083    }
2084}
2085
2086#[derive(Arbitrary)]
2087struct MultiplicativeExpression {
2088    // [117]   MultiplicativeExpression   ::=   UnaryExpression ( '*' UnaryExpression | '/' UnaryExpression )*
2089    base: UnaryExpression,
2090    elements: Vec<MultiplicativeExpressionElements>,
2091}
2092
2093#[derive(Arbitrary)]
2094enum MultiplicativeExpressionElements {
2095    Mul(UnaryExpression),
2096    Div(UnaryExpression),
2097}
2098
2099impl fmt::Display for MultiplicativeExpression {
2100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2101        write!(f, "{}", self.base)?;
2102        for element in &self.elements {
2103            match element {
2104                MultiplicativeExpressionElements::Mul(e) => write!(f, " * {e}"),
2105                MultiplicativeExpressionElements::Div(e) => write!(f, " / {e}"),
2106            }?;
2107        }
2108        Ok(())
2109    }
2110}
2111
2112#[derive(Arbitrary)]
2113enum UnaryExpression {
2114    // [135]   	UnaryExpression 	  ::=   	  '!' UnaryExpression | '+' PrimaryExpression | '-' PrimaryExpression | PrimaryExpression
2115    Not(Box<UnaryExpression>),
2116    Plus(PrimaryExpression),
2117    Minus(PrimaryExpression),
2118    Base(PrimaryExpression),
2119}
2120
2121impl fmt::Display for UnaryExpression {
2122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2123        match self {
2124            Self::Not(e) => write!(f, "!{e}"),
2125            Self::Plus(e) => write!(f, "+{e}"),
2126            Self::Minus(e) => write!(f, "-{e}"),
2127            Self::Base(e) => write!(f, "{e}"),
2128        }
2129    }
2130}
2131
2132#[expect(clippy::large_enum_variant)]
2133#[derive(Arbitrary)]
2134enum PrimaryExpression {
2135    // [119]   PrimaryExpression   ::=   BrackettedExpression | BuiltInCall | iriOrFunction | RDFLiteral | NumericLiteral | BooleanLiteral | Var
2136    Bracketted(BrackettedExpression),
2137    BuiltInCall(BuiltInCall),
2138    IriOrFunction(IriOrFunction),
2139    Literal(Literal),
2140    Var(Var),
2141}
2142
2143impl fmt::Display for PrimaryExpression {
2144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2145        match self {
2146            Self::Bracketted(e) => write!(f, "{e}"),
2147            Self::BuiltInCall(e) => write!(f, "{e}"),
2148            Self::IriOrFunction(e) => write!(f, "{e}"),
2149            Self::Literal(e) => write!(f, "{e}"),
2150            Self::Var(e) => write!(f, "{e}"),
2151        }
2152    }
2153}
2154
2155#[derive(Arbitrary)]
2156struct BrackettedExpression {
2157    // [120]   BrackettedExpression   ::=   '(' Expression ')'
2158    inner: Box<Expression>,
2159}
2160
2161impl fmt::Display for BrackettedExpression {
2162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2163        write!(f, "({})", self.inner)
2164    }
2165}
2166
2167#[derive(Arbitrary)]
2168enum BuiltInCall {
2169    // [121]   BuiltInCall   ::=     Aggregate
2170    //   | 'STR' '(' Expression ')'
2171    //   | 'LANG' '(' Expression ')'
2172    //   | 'LANGMATCHES' '(' Expression ',' Expression ')'
2173    //   | 'DATATYPE' '(' Expression ')'
2174    //   | 'BOUND' '(' Var ')'
2175    //   | 'IRI' '(' Expression ')'
2176    //   | 'URI' '(' Expression ')'
2177    //   | 'BNODE' ( '(' Expression ')' | NIL )
2178    //   | 'RAND' NIL
2179    //   | 'ABS' '(' Expression ')'
2180    //   | 'CEIL' '(' Expression ')'
2181    //   | 'FLOOR' '(' Expression ')'
2182    //   | 'ROUND' '(' Expression ')'
2183    //   | 'CONCAT' ExpressionList
2184    //   | SubstringExpression
2185    //   | 'STRLEN' '(' Expression ')'
2186    //   | StrReplaceExpression
2187    //   | 'UCASE' '(' Expression ')'
2188    //   | 'LCASE' '(' Expression ')'
2189    //   | 'ENCODE_FOR_URI' '(' Expression ')'
2190    //   | 'CONTAINS' '(' Expression ',' Expression ')'
2191    //   | 'STRSTARTS' '(' Expression ',' Expression ')'
2192    //   | 'STRENDS' '(' Expression ',' Expression ')'
2193    //   | 'STRBEFORE' '(' Expression ',' Expression ')'
2194    //   | 'STRAFTER' '(' Expression ',' Expression ')'
2195    //   | 'YEAR' '(' Expression ')'
2196    //   | 'MONTH' '(' Expression ')'
2197    //   | 'DAY' '(' Expression ')'
2198    //   | 'HOURS' '(' Expression ')'
2199    //   | 'MINUTES' '(' Expression ')'
2200    //   | 'SECONDS' '(' Expression ')'
2201    //   | 'TIMEZONE' '(' Expression ')'
2202    //   | 'TZ' '(' Expression ')'
2203    //   | 'NOW' NIL
2204    //   | 'UUID' NIL
2205    //   | 'STRUUID' NIL
2206    //   | 'MD5' '(' Expression ')'
2207    //   | 'SHA1' '(' Expression ')'
2208    //   | 'SHA256' '(' Expression ')'
2209    //   | 'SHA384' '(' Expression ')'
2210    //   | 'SHA512' '(' Expression ')'
2211    //   | 'COALESCE' ExpressionList
2212    //   | 'IF' '(' Expression ',' Expression ',' Expression ')'
2213    //   | 'STRLANG' '(' Expression ',' Expression ')'
2214    //   | 'STRDT' '(' Expression ',' Expression ')'
2215    //   | 'sameTerm' '(' Expression ',' Expression ')'
2216    //   | 'isIRI' '(' Expression ')'
2217    //   | 'isURI' '(' Expression ')'
2218    //   | 'isBLANK' '(' Expression ')'
2219    //   | 'isLITERAL' '(' Expression ')'
2220    //   | 'isNUMERIC' '(' Expression ')'
2221    //   | RegexExpression
2222    //   | ExistsFunc
2223    //   | NotExistsFunc
2224    Str(Box<Expression>),
2225    Lang(Box<Expression>),
2226    LangMatches(Box<Expression>, Box<Expression>),
2227    Datatype(Box<Expression>),
2228    Bound(Var),
2229    Iri(Box<Expression>),
2230    Uri(Box<Expression>),
2231    BNode(Box<Expression>), // TODO: no arg
2232    // TODO Rand,
2233    Abs(Box<Expression>),
2234    Ceil(Box<Expression>),
2235    Floor(Box<Expression>),
2236    Round(Box<Expression>),
2237    Concat(ExpressionList),
2238    Substring(SubstringExpression),
2239    Strlen(Box<Expression>),
2240    StrReplace(StrReplaceExpression),
2241    UCase(Box<Expression>),
2242    LCase(Box<Expression>),
2243    EncodeForUri(Box<Expression>),
2244    Contains(Box<Expression>, Box<Expression>),
2245    StrStarts(Box<Expression>, Box<Expression>),
2246    StrEnds(Box<Expression>, Box<Expression>),
2247    StrBefore(Box<Expression>, Box<Expression>),
2248    StrAfter(Box<Expression>, Box<Expression>),
2249    Year(Box<Expression>),
2250    Month(Box<Expression>),
2251    Day(Box<Expression>),
2252    Hours(Box<Expression>),
2253    Minutes(Box<Expression>),
2254    Seconds(Box<Expression>),
2255    Timezone(Box<Expression>),
2256    Tz(Box<Expression>),
2257    // TODO NOW,
2258    // TODO UUID
2259    // TODO STRUUID
2260    MD5(Box<Expression>),
2261    SHA1(Box<Expression>),
2262    SHA256(Box<Expression>),
2263    SHA384(Box<Expression>),
2264    SHA512(Box<Expression>),
2265    Coalesce(ExpressionList),
2266    If(Box<Expression>, Box<Expression>, Box<Expression>),
2267    StrLang(Box<Expression>, Box<Expression>),
2268    StrDt(Box<Expression>, Box<Expression>),
2269    SameTerm(Box<Expression>, Box<Expression>),
2270    IsIri(Box<Expression>),
2271    IsBlank(Box<Expression>),
2272    IsLiteral(Box<Expression>),
2273    IsNumeric(Box<Expression>),
2274    Regex(RegexExpression),
2275    Exists(ExistsFunc),
2276    NotExists(NotExistsFunc),
2277}
2278
2279impl fmt::Display for BuiltInCall {
2280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2281        match self {
2282            Self::Str(v) => write!(f, "STR({v})"),
2283            Self::Lang(v) => write!(f, "LANG({v})"),
2284            Self::LangMatches(a, b) => write!(f, "LangMatches({a}, {b})"),
2285            Self::Datatype(v) => write!(f, "DATATYPE({v})"),
2286            Self::Bound(v) => write!(f, "BOUND({v})"),
2287            Self::Iri(v) => write!(f, "IRI({v})"),
2288            Self::Uri(e) => write!(f, "URI({e})"),
2289            Self::BNode(v) => write!(f, "BNODE({v})"),
2290            Self::Abs(e) => write!(f, "ABS({e})"),
2291            Self::Ceil(e) => write!(f, "CEIL({e})"),
2292            Self::Floor(e) => write!(f, "FLOOR({e})"),
2293            Self::Round(e) => write!(f, "ROUND({e})"),
2294            Self::Concat(e) => write!(f, "CONCAT({e})"),
2295            Self::Strlen(e) => write!(f, "STRLEN({e})"),
2296            Self::UCase(e) => write!(f, "UCASE({e})"),
2297            Self::LCase(e) => write!(f, "LCASE({e})"),
2298            Self::EncodeForUri(e) => write!(f, "ENCODE_FOR_URI({e})"),
2299            Self::Contains(a, b) => write!(f, "CONTAINS({a}, {b})"),
2300            Self::StrStarts(a, b) => write!(f, "STRSTARTS({a}, {b})"),
2301            Self::StrEnds(a, b) => write!(f, "STRENDS({a}, {b})"),
2302            Self::StrBefore(a, b) => write!(f, "STRBEFORE({a}, {b})"),
2303            Self::StrAfter(a, b) => write!(f, "STRAFTER({a}, {b})"),
2304            Self::Year(e) => write!(f, "YEAR({e})"),
2305            Self::Month(e) => write!(f, "MONTH({e})"),
2306            Self::Day(e) => write!(f, "DAY({e})"),
2307            Self::Hours(e) => write!(f, "HOURS({e})"),
2308            Self::Minutes(e) => write!(f, "MINUTES({e})"),
2309            Self::Seconds(e) => write!(f, "SECONDS({e})"),
2310            Self::Timezone(e) => write!(f, "TIMEZONE({e})"),
2311            Self::Tz(e) => write!(f, "TZ({e})"),
2312            Self::MD5(e) => write!(f, "MD5({e})"),
2313            Self::SHA1(e) => write!(f, "SH1({e})"),
2314            Self::SHA256(e) => write!(f, "SHA256({e})"),
2315            Self::SHA384(e) => write!(f, "SHA384({e})"),
2316            Self::SHA512(e) => write!(f, "SHA512({e})"),
2317            Self::Coalesce(vs) => write!(f, "COALESCE{vs}"),
2318            Self::If(a, b, c) => write!(f, "IF({a}, {b}, {c})"),
2319            Self::StrLang(a, b) => write!(f, "STRLANG({a}, {b})"),
2320            Self::StrDt(a, b) => write!(f, "STRDT({a}, {b})"),
2321            Self::SameTerm(a, b) => write!(f, "sameTerm({a}, {b})"),
2322            Self::IsIri(e) => write!(f, "isIRI({e})"),
2323            Self::IsBlank(e) => write!(f, "isBlank({e})"),
2324            Self::IsLiteral(e) => write!(f, "isLiteral({e})"),
2325            Self::IsNumeric(e) => write!(f, "isNumeric({e})"),
2326            Self::Exists(e) => write!(f, "{e}"),
2327            Self::NotExists(e) => write!(f, "{e}"),
2328            Self::Substring(e) => write!(f, "{e}"),
2329            Self::StrReplace(e) => write!(f, "{e}"),
2330            Self::Regex(e) => write!(f, "{e}"),
2331        }
2332    }
2333}
2334
2335#[derive(Arbitrary)]
2336struct RegexExpression {
2337    // [122]  	RegexExpression	  ::=  	'REGEX' '(' Expression ',' Expression ( ',' Expression )? ')'
2338    arg1: Box<Expression>,
2339    arg2: Box<Expression>,
2340    arg3: Option<Box<Expression>>,
2341}
2342
2343impl fmt::Display for RegexExpression {
2344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2345        write!(f, "REGEX({}, {}", self.arg1, self.arg2)?;
2346        if let Some(arg3) = &self.arg3 {
2347            write!(f, ", {arg3}")?;
2348        }
2349        write!(f, ")")
2350    }
2351}
2352
2353#[derive(Arbitrary)]
2354struct SubstringExpression {
2355    // [123]  	SubstringExpression	  ::=  	'SUBSTR' '(' Expression ',' Expression ( ',' Expression )? ')'
2356    arg1: Box<Expression>,
2357    arg2: Box<Expression>,
2358    arg3: Option<Box<Expression>>,
2359}
2360
2361impl fmt::Display for SubstringExpression {
2362    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2363        write!(f, "SUBSTR({}, {}", self.arg1, self.arg2)?;
2364        if let Some(arg3) = &self.arg3 {
2365            write!(f, ", {arg3}")?;
2366        }
2367        write!(f, ")")
2368    }
2369}
2370
2371#[derive(Arbitrary)]
2372struct StrReplaceExpression {
2373    // [124]  	StrReplaceExpression	  ::=  	'REPLACE' '(' Expression ',' Expression ',' Expression ( ',' Expression )? ')'
2374    arg1: Box<Expression>,
2375    arg2: Box<Expression>,
2376    arg3: Box<Expression>,
2377    arg4: Option<Box<Expression>>,
2378}
2379
2380impl fmt::Display for StrReplaceExpression {
2381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2382        write!(f, "SUBSTR({}, {}, {}", self.arg1, self.arg2, self.arg3)?;
2383        if let Some(arg4) = &self.arg4 {
2384            write!(f, ", {arg4}")?;
2385        }
2386        write!(f, ")")
2387    }
2388}
2389
2390#[derive(Arbitrary)]
2391struct ExistsFunc {
2392    // [125]   ExistsFunc   ::=   'EXISTS' GroupGraphPattern
2393    pattern: GroupGraphPattern,
2394}
2395
2396impl fmt::Display for ExistsFunc {
2397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2398        write!(f, "EXISTS {}", self.pattern)
2399    }
2400}
2401
2402#[derive(Arbitrary)]
2403struct NotExistsFunc {
2404    // [126]   NotExistsFunc   ::=   'NOT' 'EXISTS' GroupGraphPattern
2405    pattern: GroupGraphPattern,
2406}
2407
2408impl fmt::Display for NotExistsFunc {
2409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2410        write!(f, "NOT EXISTS {}", self.pattern)
2411    }
2412}
2413
2414#[derive(Arbitrary)]
2415enum IriOrFunction {
2416    // [128]   iriOrFunction   ::=   iri ArgList?
2417    Iri(Iri),
2418    Function(FunctionCall),
2419}
2420
2421impl fmt::Display for IriOrFunction {
2422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2423        match self {
2424            IriOrFunction::Iri(i) => write!(f, "{i}"),
2425            IriOrFunction::Function(func) => write!(f, "{func}"),
2426        }
2427    }
2428}
2429
2430struct Literal {
2431    // [129]   RDFLiteral               ::=   String ( LANGTAG | ( '^^' iri ) )?
2432    // [130]   NumericLiteral           ::=   NumericLiteralUnsigned | NumericLiteralPositive | NumericLiteralNegative
2433    // [131]   NumericLiteralUnsigned   ::=   INTEGER | DECIMAL | DOUBLE
2434    // [132]   NumericLiteralPositive   ::=   INTEGER_POSITIVE | DECIMAL_POSITIVE | DOUBLE_POSITIVE
2435    // [133]   NumericLiteralNegative   ::=   INTEGER_NEGATIVE | DECIMAL_NEGATIVE | DOUBLE_NEGATIVE
2436    // [134]   BooleanLiteral           ::=   'true' | 'false'
2437    value: &'static str,
2438}
2439
2440impl Arbitrary<'_> for Literal {
2441    fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> {
2442        Ok(Self {
2443            value: u.choose(LITERALS.as_slice())?,
2444        })
2445    }
2446
2447    fn size_hint(depth: usize) -> (usize, Option<usize>) {
2448        <u8 as Arbitrary>::size_hint(depth)
2449    }
2450}
2451
2452impl fmt::Display for Literal {
2453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2454        write!(f, "{}", self.value)
2455    }
2456}
2457
2458struct Iri {
2459    // [136]   iri   ::=   IRIREF | PrefixedName
2460    value: u8,
2461}
2462
2463impl Arbitrary<'_> for Iri {
2464    fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> {
2465        Ok(Self {
2466            value: u.int_in_range(1..=NUMBER_OF_NAMED_NODES)?,
2467        })
2468    }
2469
2470    fn size_hint(depth: usize) -> (usize, Option<usize>) {
2471        <u8 as Arbitrary>::size_hint(depth)
2472    }
2473}
2474
2475impl fmt::Display for Iri {
2476    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2477        write!(f, " <http://example.org/{}> ", self.value)
2478    }
2479}