1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Syntax definition and incomplete syntax error types.
//!
//! This module provides types for representing syntax elements with a known number
//! of components, and errors for tracking missing components during parsing.
//!
//! # Design Philosophy
//!
//! When parsing syntax elements that require multiple components (like variable declarations,
//! function definitions, etc.), it's valuable to track *all* missing components rather than
//! failing on the first missing one. This enables:
//!
//! - Better error messages showing all missing parts
//! - Faster development iteration (see all errors at once)
//! - More helpful IDE diagnostics
//!
//! # Examples
//!
//! ```rust
//! # {
//! use tokit::{utils::{typenum::{self, U3}, GenericArrayDeque, Span}, syntax::Syntax, error::IncompleteSyntax};
//! use core::fmt;
//!
//! #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
//! struct MyLanguage;
//!
//! #[derive(Debug, Clone, PartialEq, Eq, Hash)]
//! enum WhileComponent {
//! WhileKeyword,
//! Condition,
//! Body,
//! }
//!
//! impl fmt::Display for WhileComponent {
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! match self {
//! Self::WhileKeyword => write!(f, "'while' keyword"),
//! Self::Condition => write!(f, "condition"),
//! Self::Body => write!(f, "body"),
//! }
//! }
//! }
//!
//! struct WhileLoop;
//!
//! impl Syntax for WhileLoop {
//! type Lang = MyLanguage;
//! type Component = WhileComponent;
//! type COMPONENTS = U3;
//! type REQUIRED = U3;
//!
//! fn possible_components() -> &'static GenericArrayDeque<Self::Component, U3> {
//! static COMPONENTS: GenericArrayDeque<WhileComponent, tokit::utils::typenum::U3> = {
//! let mut deque = GenericArrayDeque::new();
//! deque.push_back(WhileComponent::WhileKeyword);
//! deque.push_back(WhileComponent::Condition);
//! deque.push_back(WhileComponent::Body);
//! deque
//! };
//! &COMPONENTS
//! }
//!
//! fn required_components() -> &'static GenericArrayDeque<Self::Component, Self::REQUIRED> {
//! static REQUIRED: GenericArrayDeque<WhileComponent, tokit::utils::typenum::U3> = {
//! let mut deque = GenericArrayDeque::new();
//! deque.push_back(WhileComponent::WhileKeyword);
//! deque.push_back(WhileComponent::Condition);
//! deque.push_back(WhileComponent::Body);
//! deque
//! };
//! &REQUIRED
//! }
//! }
//!
//! let mut error = IncompleteSyntax::<WhileLoop>::new(Span::new(10, 15), WhileComponent::Condition);
//! assert_eq!(error.len(), 1);
//! # }
//! ```
use ArrayLength;
use ;
/// A trait representing a syntax with a type-level number of components.
///
/// This trait defines the structure of a syntax element that has a known number
/// of required components. It uses `typenum` for type-level component count,
/// enabling compile-time arithmetic and better integration with generic-array-based code.
///
/// # Type Parameters
///
/// - `Component`: The type representing individual syntax components (usually an enum)
/// - `COMPONENTS`: A type-level unsigned integer (via `ArrayLength`) specifying component count
///
/// # Examples
///
/// ```rust
/// # {
/// use tokit::{utils::{typenum, GenericArrayDeque}, syntax::{Syntax, Language}};
/// use typenum::U5;
/// use core::fmt;
///
/// struct MyLanguage;
///
/// impl Language for MyLanguage {
/// type SyntaxKind = (); // () is a placeholder
/// }
///
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// enum LetStatementComponent {
/// LetKeyword,
/// Identifier,
/// Equals,
/// Expression,
/// Semicolon,
/// }
///
/// impl fmt::Display for LetStatementComponent {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// match self {
/// Self::LetKeyword => write!(f, "'let' keyword"),
/// Self::Identifier => write!(f, "identifier"),
/// Self::Equals => write!(f, "'=' operator"),
/// Self::Expression => write!(f, "expression"),
/// Self::Semicolon => write!(f, "';' semicolon"),
/// }
/// }
/// }
///
/// struct LetStatement;
///
/// impl Syntax for LetStatement {
/// type Lang = MyLanguage;
/// const KIND: () = (); // () is a placeholder
/// type Component = LetStatementComponent;
/// type COMPONENTS = U5;
/// type REQUIRED = U5;
///
/// fn possible_components() -> &'static GenericArrayDeque<Self::Component, Self::COMPONENTS> {
/// static COMPONENTS: GenericArrayDeque<LetStatementComponent, typenum::U5> = {
/// let mut deque = GenericArrayDeque::new();
/// deque.push_back(LetStatementComponent::LetKeyword);
/// deque.push_back(LetStatementComponent::Identifier);
/// deque.push_back(LetStatementComponent::Equals);
/// deque.push_back(LetStatementComponent::Expression);
/// deque.push_back(LetStatementComponent::Semicolon);
/// deque
/// };
/// &COMPONENTS
/// }
///
/// fn required_components() -> &'static GenericArrayDeque<Self::Component, Self::REQUIRED> {
/// static REQUIRED: GenericArrayDeque<LetStatementComponent, typenum::U5> = {
/// let mut deque = GenericArrayDeque::new();
/// deque.push_back(LetStatementComponent::LetKeyword);
/// deque.push_back(LetStatementComponent::Identifier);
/// deque.push_back(LetStatementComponent::Equals);
/// deque.push_back(LetStatementComponent::Expression);
/// deque.push_back(LetStatementComponent::Semicolon);
/// deque
/// };
/// &REQUIRED
/// }
/// }
/// # }
/// ```
/// A trait representing an AST node associated with a syntax definition.
///
/// This trait creates a type-level bridge between AST node types and their corresponding
/// `Syntax` types, enabling generic, type-safe error handling and parser implementation.
/// By associating an AST node with its syntax structure, we can automatically derive
/// error construction logic and write language-polymorphic parsers.
///
/// # Design Philosophy
///
/// When parsing AST nodes, incomplete syntax errors need to know which syntax element
/// failed to parse. The `AstNode` trait makes this relationship explicit at the type level:
///
/// - Each AST node type declares its corresponding `Syntax` type
/// - Generic code can use `T::Syntax` to construct appropriate `IncompleteSyntax<T::Syntax>` errors
/// - The `Lang` parameter enables the same structural node (e.g., `Name<S>`) to have
/// different syntax types in different language dialects
///
/// # Benefits
///
/// 1. **Type Safety**: Impossible to construct errors with the wrong syntax type
/// 2. **Generic Parsers**: Write parsers that work for any `T: AstNode<Lang>`
/// 3. **Discoverability**: Given an AST node, easily find its syntax definition
/// 4. **Language Polymorphism**: Same node structure, different syntax per dialect
/// 5. **Reduced Boilerplate**: Generic error handling without manual trait implementations
///
/// # Type Parameters
///
/// - `Lang`: The language or dialect this AST node belongs to. This enables:
/// - Distinguishing GraphQL from GraphQLx nodes
/// - Supporting multiple language dialects in one codebase
/// - Language-specific syntax customization
///
/// # Examples
///
/// ## Basic Implementation
///
/// ```rust
/// # {
/// use tokit::{utils::{GenericArrayDeque, typenum::U2, Span}, syntax::{Syntax, AstNode, Language}, error::IncompleteSyntax};
/// use core::fmt;
///
/// // Define a language
/// #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// struct MyLanguage;
///
/// impl Language for MyLanguage {
/// type SyntaxKind = (); // () is a placeholder
/// }
///
/// // Define syntax components
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// enum VariableComponent {
/// Dollar,
/// Name,
/// }
///
/// impl fmt::Display for VariableComponent {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// match self {
/// Self::Dollar => write!(f, "'$' prefix"),
/// Self::Name => write!(f, "variable name"),
/// }
/// }
/// }
///
/// // Define syntax type
/// struct VariableSyntax;
///
/// impl Syntax for VariableSyntax {
/// type Lang = MyLanguage;
/// const KIND: () = (); // () is a placeholder
/// type Component = VariableComponent;
/// type COMPONENTS = U2;
/// type REQUIRED = U2;
///
/// fn possible_components() -> &'static GenericArrayDeque<Self::Component, Self::COMPONENTS> {
/// const COMPONENTS: &GenericArrayDeque<VariableComponent, U2> = &GenericArrayDeque::from_array([VariableComponent::Dollar, VariableComponent::Name]);
/// COMPONENTS
/// }
///
/// fn required_components() -> &'static GenericArrayDeque<Self::Component, Self::REQUIRED> {
/// const REQUIRED: &GenericArrayDeque<VariableComponent, U2> = &GenericArrayDeque::from_array([VariableComponent::Dollar, VariableComponent::Name]);
/// REQUIRED
/// }
/// }
///
/// // Define AST node
/// struct Variable {
/// name: String,
/// }
///
/// // Implement AstNode to bridge AST and Syntax
/// impl AstNode<MyLanguage> for Variable {
/// type Syntax = VariableSyntax;
/// }
///
/// // Now generic code can use T::Syntax automatically
/// fn create_incomplete_error<T>(span: Span, component: <T::Syntax as Syntax>::Component) -> IncompleteSyntax<T::Syntax>
/// where
/// T: AstNode<MyLanguage>,
/// {
/// IncompleteSyntax::new(span, component)
/// }
///
/// let error = create_incomplete_error::<Variable>(
/// Span::new(0, 3),
/// VariableComponent::Dollar
/// );
/// # }
/// ```
///
/// ## Generic Parser with AstNode
///
/// ```rust,ignore
/// use tokit::{
/// chumsky::{Parser, extra::ParserExtra},
/// syntax::AstNode,
/// error::IncompleteSyntax,
/// };
///
/// // Generic parser that works for any AST node type
/// fn parse_node<'a, T, I, Token, Error, E>() -> impl Parser<'a, I, T, E>
/// where
/// T: AstNode<Lang> + Parseable<'a, I, Token, Error>,
/// Error: From<IncompleteSyntax<T::Syntax>>,
/// E: ParserExtra<'a, I, Error = Error>,
/// {
/// // Parser automatically knows how to construct errors using T::Syntax
/// T::parser()
/// .recover_with(|error| {
/// // Error recovery using T::Syntax automatically
/// // ...
/// })
/// }
/// ```
///
/// ## Language Polymorphism
///
/// ```rust,ignore
/// // Same structure, different syntax per language
/// struct Name<S> {
/// source: S,
/// }
///
/// // GraphQL implementation
/// impl<S> AstNode<GraphQL> for Name<S> {
/// type Syntax = GraphQLNameSyntax;
/// }
///
/// // GraphQLx implementation (extended dialect)
/// impl<S> AstNode<GraphQLx> for Name<S> {
/// type Syntax = GraphQLxNameSyntax; // Different syntax rules
/// }
/// ```
///
/// # Common Patterns
///
/// ## With Generic AST Nodes
///
/// For AST nodes with generic parameters, implement `AstNode` for the generic type:
///
/// ```rust,ignore
/// struct TypeDefinition<Name, Directives> {
/// name: Name,
/// directives: Option<Directives>,
/// }
///
/// impl<Name, Directives> AstNode<GraphQL> for TypeDefinition<Name, Directives> {
/// type Syntax = TypeDefinitionSyntax;
/// }
/// ```
///
/// ## Multiple Language Support
///
/// The same node structure can implement `AstNode` for multiple languages:
///
/// ```rust,ignore
/// impl<S> AstNode<GraphQL> for Variable<S> {
/// type Syntax = GraphQLVariableSyntax;
/// }
///
/// impl<S> AstNode<GraphQLx> for Variable<S> {
/// type Syntax = GraphQLxVariableSyntax;
/// }
/// ```
///
/// # See Also
///
/// - [`Syntax`]: Defines the structure and components of syntax elements
/// - [`IncompleteSyntax`](crate::error::IncompleteSyntax): Error type for tracking missing syntax components
/// - [`Parseable`](crate::chumsky::Parseable): Trait for types that can be parsed
/// Marker trait tying a language to its syntax kinds.
///
/// The `Language` trait connects your parser/AST to the concrete set of syntax kinds
/// (tokens, node tags, etc.) that belong to a language. Implement it once per language or
/// dialect so generic parsing infrastructure can stay agnostic of the actual enum.
///
/// ## Example
///
/// ```rust,ignore
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// pub enum MySyntaxKind {
/// Identifier,
/// Number,
/// // ...
/// }
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// pub struct MyLanguage;
///
/// impl Language for MyLanguage {
/// type SyntaxKind = MySyntaxKind;
/// }
/// ```