laburnum-syntax-macro 0.1.0

Proc-macros for defining CST and AST node types in language frontends built with the laburnum LSP framework.
Documentation
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

use {
  crate::error::{Error, ErrorAccumulator},
  proc_macro2::TokenStream,
  quote::{ToTokens, spanned::Spanned as quote_spanned},
  syn::{Item, Type, spanned::Spanned},
};

// The AST is very simple for this macro, as you can _only_ attach it to
// a function.
#[derive(Debug, Clone)]
pub struct Ast {
  pub name: String,
  pub fields: Vec<Field>,
}

#[derive(Debug, Clone)]
pub struct Field {
  pub(crate) name: String,

  pub(crate) ty: FieldType,

  // the field is wrapped in an outer Vec<T>
  // Vec can only contain NodeId (which is implicit)
  pub(crate) is_vec: bool,

  // the field is wrapped in an outer Option<T>
  pub(crate) is_optional: bool,

  // the field is wrapped in Field<T> indicating it is embedded on the struct
  pub(crate) is_field: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum FieldType {
  Unknown,
  #[allow(dead_code)]
  Error(String),

  // Literal path to a type
  Path(String),
  // The type is a literal Enum
  Enum(String),
  // Only a single Node type is valid
  SingleNode(String),
  // Multiple Node types are valid
  MultipleNode(Vec<String>),

  // An existing literal Enum, that maps to a Node
  EnumNodeId(String),
  // Use the literal provided type
  Literal(&'static str),
  // The type is a string
  String,
  // laburnum::Span - for storing span references
  Span,
  // laburnum::Ident - for storing identifier hashes
  Ident,
  // laburnum::Spanned<laburnum::Ident> - (Ident, Span) tuple
  SpannedIdent,
}

// Parsing a field
//
// In the CST
// -> Option<FieldType> = { is_option: true, ty: FieldType }
// -> FieldType = { is_option: false, ty: FieldType }
//
// In the AST, a field is either
//
// - NodeId<T>, which means there's only one type of node that can go there
// - NodeId<A, B, C>, which means there's an enum of nodes that can go there
// - Vec<T>, which means the underlying type is a Vec<NodeId>
//
// Fields wrapped in Option<T> don't need to be `Some` for the AST to be valid.
// But all fields are implemented as `Option<T>` in the AST.

pub fn parse(ts: TokenStream) -> Result<Ast, syn::Error> {
  let item = ts;
  let span = item.__span();

  match syn::parse2::<Item>(item) {
    | Ok(Item::Struct(item_stct)) => {
      let name = item_stct.ident.clone().to_string().trim().to_string();

      let fields = {
        match item_stct.fields {
          | syn::Fields::Named(fields_named) => {
            parse_fields_with_accumulation(&fields_named.named)?
          },
          | _ => unimplemented!(),
        }
      };

      Ok(Ast { name, fields })
    },
    | Ok(_) => {
      let error_details = Error::ParseItemNotStruct(span).get();
      let mut syn_error =
        syn::Error::new(error_details.span, &error_details.message);

      // Add help and hints if available
      if let Some(help) = &error_details.help {
        let help_error =
          syn::Error::new(error_details.span, format!("help: {help}"));
        syn_error.combine(help_error);
      }
      if let Some(hints) = &error_details.hints {
        let hints_error =
          syn::Error::new(error_details.span, format!("hint: {hints}"));
        syn_error.combine(hints_error);
      }

      Err(syn_error)
    },
    | Err(parse_error) => {
      let error_details = Error::Parser(span).get();
      let mut combined_error =
        syn::Error::new(error_details.span, &error_details.message);
      combined_error.combine(parse_error);
      Err(combined_error)
    },
  }
}

/// Parse all fields and accumulate any errors found
fn parse_fields_with_accumulation(
  fields: &syn::punctuated::Punctuated<syn::Field, syn::Token![,]>,
) -> Result<Vec<Field>, syn::Error> {
  let mut accumulator = ErrorAccumulator::new();
  let mut parsed_fields = Vec::new();

  for field in fields {
    match parse_field(field) {
      | Ok(parsed_field) => {
        parsed_fields.push(parsed_field);
      },
      | Err(error) => {
        accumulator.add_error(error);
      },
    }
  }

  accumulator.into_result(parsed_fields)
}

fn parse_field(f: &syn::Field) -> Result<Field, Error> {
  let name = match &f.ident {
    | Some(ident) => ident.to_string(),
    | None => {
      return Err(Error::MissingFieldIdentifier(f.span()));
    },
  };

  match &f.ty {
    | Type::Path(type_path) => {
      let mut segments = type_path.path.segments.clone().into_iter();
      let Some(seg) = segments.next() else {
        return Err(Error::EmptyTypePath(type_path.span()));
      };

      let fld = Field {
        name,
        ty: FieldType::Unknown,
        is_vec: false,
        is_optional: false,
        is_field: false,
      };

      parse_path_segment(type_path, &seg, fld)
    },
    | _ => Err(Error::UnsupportedFieldType(
      f.ty.span(),
      format!("{:?}", f.ty),
    )),
  }
}

// TODO: all these errors could be helpful (gold-1up)

fn format_path(ts: &TokenStream) -> String {
  ts.to_string().replace(' ', "")
}

fn parse_path_segment(
  type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
) -> Result<Field, Error> {
  let s = seg.ident.clone().to_string();

  // TODO: rename these to match the validation requirement (gold-5v3)
  // ie, OneOf, OneOrMore, ZeroOrMore, ZeroOrOne
  match s.as_str() {
    | "Option" => parse_field_option(type_path, seg, f),
    | "NodeId" => parse_field_nodeid(type_path, seg, f),
    | "EnumNodeId" => parse_field_enum_nodeid(type_path, seg, f),
    | "Vec" => parse_field_vec(type_path, seg, f),
    | "Field" => parse_field_field(type_path, seg, f),
    | "Enum" => parse_field_enum(type_path, seg, f),
    | "Spanned" => parse_field_spanned(type_path, seg, f),
    | "crate" => Ok(Field {
      ty: FieldType::Path(format_path(&type_path.to_token_stream())),
      ..f
    }),

    // Terminals
    | "String" => parse_field_string(type_path, seg, f),
    | "Span" => Ok(Field {
      ty: FieldType::Span,
      ..f
    }),
    | "Ident" => Ok(Field {
      ty: FieldType::Ident,
      ..f
    }),
    | "bool" => parse_field_literal(type_path, seg, f, "bool"),
    | "usize" => parse_field_literal(type_path, seg, f, "usize"),
    | "u8" => parse_field_literal(type_path, seg, f, "u8"),
    | "u16" => parse_field_literal(type_path, seg, f, "u16"),
    | "u32" => parse_field_literal(type_path, seg, f, "u32"),
    | "u64" => parse_field_literal(type_path, seg, f, "u64"),
    | "u128" => parse_field_literal(type_path, seg, f, "u128"),
    | "isize" => parse_field_literal(type_path, seg, f, "isize"),
    | "i8" => parse_field_literal(type_path, seg, f, "i8"),
    | "i16" => parse_field_literal(type_path, seg, f, "i16"),
    | "i32" => parse_field_literal(type_path, seg, f, "i32"),
    | "i64" => parse_field_literal(type_path, seg, f, "i64"),
    | "i128" => parse_field_literal(type_path, seg, f, "i128"),
    | "f32" => parse_field_literal(type_path, seg, f, "f32"),
    | "f64" => parse_field_literal(type_path, seg, f, "f64"),
    | _ => {
      let type_name: &'static str =
        Box::leak(seg.ident.to_string().into_boxed_str());
      parse_field_literal(type_path, seg, f, type_name)
    },
  }
}

fn parse_field_nodeid(
  _type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
) -> Result<Field, Error> {
  if seg.ident.to_string().as_str() != "NodeId" {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "Expected NodeId to have type arguments".to_string(),
    ));
  }

  let field_ty = match &seg.arguments {
    | syn::PathArguments::AngleBracketed(args) => {
      let args_len = args.args.len();

      match args_len {
        | 0 => {
          return Err(Error::InvalidFieldTypeMessage(
            seg.__span(),
            "Expected NodeId to have type arguments".to_string(),
          ));
        },
        | 1 => {
          match args.args.first().unwrap() {
            | syn::GenericArgument::Type(ty) => {
              FieldType::SingleNode(format_path(&ty.to_token_stream()))
            },
            | _ => {
              return Err(Error::InvalidFieldTypeMessage(
                seg.__span(),
                "Expected NodeId to have type arguments".to_string(),
              ));
            },
          }
        },
        | _ => {
          let mut tys = Vec::with_capacity(args_len);

          for arg in args.args.iter() {
            match arg {
              | syn::GenericArgument::Type(ty) => {
                tys.push(format_path(&ty.to_token_stream()));
              },
              | _ => {
                return Err(Error::InvalidFieldTypeMessage(
                  seg.__span(),
                  "Expected NodeId to have type arguments".to_string(),
                ));
              },
            }
          }

          FieldType::MultipleNode(tys)
        },
      }
    },
    | _ => {
      return Err(Error::InvalidFieldTypeMessage(
        seg.__span(),
        "Expected NodeId to have at least one type argument".to_string(),
      ));
    },
  };

  Ok(Field { ty: field_ty, ..f })
}

fn parse_field_enum_nodeid(
  _type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
) -> Result<Field, Error> {
  if seg.ident.to_string().as_str() != "EnumNodeId" {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "Expected NodeId to have type arguments".to_string(),
    ));
  }

  let field_ty = match &seg.arguments {
    | syn::PathArguments::AngleBracketed(args) => match args.args.len() {
      | 0 => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Expected EnumNodeId to have type argument".to_string(),
        ));
      },
      | 1 => match args.args.first().unwrap() {
        | syn::GenericArgument::Type(ty) => {
          FieldType::EnumNodeId(format_path(&ty.to_token_stream()))
        },
        | _ => {
          return Err(Error::InvalidFieldTypeMessage(
            seg.__span(),
            "Expected EnumNodeId to have type arguments".to_string(),
          ));
        },
      },
      | _ => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Expected EnumNodeId to have only one type argument".to_string(),
        ));
      },
    },
    | _ => {
      return Err(Error::InvalidFieldTypeMessage(
        seg.__span(),
        "Expected EnumNodeId to have one type argument".to_string(),
      ));
    },
  };

  Ok(Field { ty: field_ty, ..f })
}

fn parse_field_field(
  _type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
) -> Result<Field, Error> {
  if seg.ident.to_string().as_str() != "Field" {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "Expected Field to have type arguments".to_string(),
    ));
  }

  let field = match &seg.arguments {
    | syn::PathArguments::AngleBracketed(args) => match args.args.len() {
      | 0 => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Expected Field to have type arguments".to_string(),
        ));
      },
      | 1 => match args.args.first().unwrap() {
        | syn::GenericArgument::Type(ty) => match ty {
          | Type::Path(p) => {
            let mut segments = p.path.segments.clone().into_iter();
            let seg = segments
              .next()
              .expect("Expected Type::Path to have at least one segment");
            parse_path_segment(p, &seg, f)?
          },
          | _ => {
            return Err(Error::InvalidFieldTypeMessage(
              seg.__span(),
              "Invalid argument type for 'Field'".to_string(),
            ));
          },
        },
        | _ => {
          return Err(Error::InvalidFieldTypeMessage(
            seg.__span(),
            "Expected Field to have type arguments".to_string(),
          ));
        },
      },
      | _ => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Expected Field to have only on type argument".to_string(),
        ));
      },
    },
    | _ => {
      return Err(Error::InvalidFieldTypeMessage(
        seg.__span(),
        "Expected Field to have at least one type argument".to_string(),
      ));
    },
  };

  Ok(Field {
    is_field: true,
    ..field
  })
}

fn parse_field_enum(
  _type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
) -> Result<Field, Error> {
  if seg.ident.to_string().as_str() != "Enum" {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "Expected Field to have type arguments".to_string(),
    ));
  }

  let field_ty = match &seg.arguments {
    | syn::PathArguments::AngleBracketed(args) => match args.args.len() {
      | 0 => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Expected NodeId to have type arguments".to_string(),
        ));
      },
      | 1 => match args.args.first().unwrap() {
        | syn::GenericArgument::Type(ty) => {
          FieldType::Enum(format_path(&ty.to_token_stream()))
        },
        | _ => {
          return Err(Error::InvalidFieldTypeMessage(
            seg.__span(),
            "Expected NodeId to have type arguments".to_string(),
          ));
        },
      },
      | _ => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Expected Enum to have only one type arguments".to_string(),
        ));
      },
    },
    | _ => {
      return Err(Error::InvalidFieldTypeMessage(
        seg.__span(),
        "Expected NodeId to have at least one type argument".to_string(),
      ));
    },
  };

  Ok(Field { ty: field_ty, ..f })
}

fn parse_field_vec(
  _type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
) -> Result<Field, Error> {
  if seg.ident.to_string().as_str() != "Vec" {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "Expected Vec".to_string(),
    ));
  }

  let field = match &seg.arguments {
    | syn::PathArguments::AngleBracketed(args) => match args.args.len() {
      | 0 => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Vec must have at least one type argument".to_string(),
        ));
      },
      | 1 => match args.args.first().unwrap() {
        | syn::GenericArgument::Type(ty) => match ty {
          | Type::Path(p) => {
            let mut segments = p.path.segments.clone().into_iter();
            let seg = segments
              .next()
              .expect("Expected Type::Path to have at least one segment");

            parse_path_segment(p, &seg, f)?
          },
          | _ => {
            return Err(Error::InvalidFieldTypeMessage(
              seg.__span(),
              "Invalid argument type for 'Vec'".to_string(),
            ));
          },
        },
        | _ => {
          return Err(Error::InvalidFieldTypeMessage(
            seg.__span(),
            "Expected Vec to have type arguments".to_string(),
          ));
        },
      },
      | _ => Field {
        ty: FieldType::MultipleNode(
          args
            .args
            .iter()
            .map(|a| format_path(&a.to_token_stream()))
            .collect(),
        ),
        ..f
      },
    },
    | _ => {
      return Err(Error::InvalidFieldTypeMessage(
        seg.__span(),
        "Vec must have at least one type argument".to_string(),
      ));
    },
  };

  Ok(Field {
    is_vec: true,
    ..field
  })
}

fn parse_field_option(
  type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
) -> Result<Field, Error> {
  if seg.ident.to_string().as_str() != "Option" {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "Invalid field type: expected 'Option'".to_string(),
    ));
  }

  let field = match &seg.arguments {
    | syn::PathArguments::AngleBracketed(args) => match args.args.len() {
      | 0 => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "No arguments provided for 'Option' type".to_string(),
        ));
      },
      | 1 => match args.args.first().unwrap() {
        | syn::GenericArgument::Type(ty) => match ty {
          | Type::Path(p) => {
            let mut segments = p.path.segments.clone().into_iter();
            let seg = segments
              .next()
              .expect("Expected Type::Path to have at least one segment");
            parse_path_segment(type_path, &seg, f)?
          },
          | _ => {
            return Err(Error::InvalidFieldTypeMessage(
              seg.__span(),
              "Invalid argument type for 'Option'".to_string(),
            ));
          },
        },
        | _ => {
          return Err(Error::InvalidFieldTypeMessage(
            seg.__span(),
            "Invalid generic argument for 'Option'".to_string(),
          ));
        },
      },
      | _ => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Invalid number of arguments for 'Option'".to_string(),
        ));
      },
    },
    | _ => {
      return Err(Error::InvalidFieldTypeMessage(
        seg.__span(),
        "Invalid path arguments: expected 'AngleBracketed'".to_string(),
      ));
    },
  };

  Ok(Field {
    is_optional: true,
    ..field
  })
}

fn parse_field_string(
  _type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
) -> Result<Field, Error> {
  if seg.ident.to_string().as_str() != "String" {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "Invalid field type: expected 'String'".to_string(),
    ));
  }

  if !seg.arguments.is_empty() {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "String does not take any arguments".to_string(),
    ));
  }

  Ok(Field {
    ty: FieldType::String,
    ..f
  })
}

fn parse_field_literal(
  _type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
  lit_ty: &'static str,
) -> Result<Field, Error> {
  if !seg.arguments.is_empty() {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "literal types do not take any arguments".to_string(),
    ));
  }

  Ok(Field {
    ty: FieldType::Literal(lit_ty),
    ..f
  })
}

fn parse_field_spanned(
  _type_path: &syn::TypePath,
  seg: &syn::PathSegment,
  f: Field,
) -> Result<Field, Error> {
  if seg.ident.to_string().as_str() != "Spanned" {
    return Err(Error::InvalidFieldTypeMessage(
      seg.__span(),
      "Expected Spanned".to_string(),
    ));
  }

  let field_ty = match &seg.arguments {
    | syn::PathArguments::AngleBracketed(args) => match args.args.len() {
      | 0 => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Expected Spanned to have type argument".to_string(),
        ));
      },
      | 1 => match args.args.first().unwrap() {
        | syn::GenericArgument::Type(syn::Type::Path(p)) => {
          let inner_seg = p.path.segments.first();
          if let Some(inner_seg) = inner_seg {
            if inner_seg.ident.to_string().as_str() == "Ident" {
              FieldType::SpannedIdent
            } else {
              return Err(Error::InvalidFieldTypeMessage(
                inner_seg.__span(),
                format!(
                  "Expected Spanned<Ident>, found Spanned<{}>",
                  inner_seg.ident
                ),
              ));
            }
          } else {
            return Err(Error::InvalidFieldTypeMessage(
              args.__span(),
              "Expected Spanned<Ident>".to_string(),
            ));
          }
        },
        | _ => {
          return Err(Error::InvalidFieldTypeMessage(
            seg.__span(),
            "Expected Spanned<Ident>".to_string(),
          ));
        },
      },
      | _ => {
        return Err(Error::InvalidFieldTypeMessage(
          seg.__span(),
          "Spanned only takes one type argument".to_string(),
        ));
      },
    },
    | _ => {
      return Err(Error::InvalidFieldTypeMessage(
        seg.__span(),
        "Expected Spanned to have type argument".to_string(),
      ));
    },
  };

  Ok(Field { ty: field_ty, ..f })
}