1use ecow::EcoString;
2
3use super::{ParamMode, Parser};
4use crate::ast::{
5 Annotation, Attribute, AttributeArg, EnumFieldDefinition, EnumVariant, Expression, Generic,
6 ParentInterface, Span, StructFieldDefinition, StructKind, VariantFields, Visibility,
7};
8use crate::lex::Token;
9use crate::lex::TokenKind::*;
10use crate::parse::error::ParseError;
11use crate::types::Type;
12
13impl<'source> Parser<'source> {
14 pub(crate) fn parse_attributes(&mut self) -> Vec<Attribute> {
15 let mut attributes = vec![];
16 loop {
17 self.advance_if(Semicolon);
18 if !self.is(Hash) {
19 break;
20 }
21 if let Some(attribute) = self.parse_attribute() {
22 attributes.push(attribute);
23 }
24 }
25 attributes
26 }
27
28 fn parse_attribute(&mut self) -> Option<Attribute> {
29 let start = self.current_token();
30 self.ensure(Hash);
31
32 if !self.is(LeftSquareBracket) {
33 self.track_error("expected `[` after `#`", "Add `[` to start the attribute");
34 return None;
35 }
36 self.next();
37
38 if !self.is(Identifier) {
39 self.track_error(
40 "expected attribute name",
41 "Add an attribute name like `json` or `db`",
42 );
43 while self.is_not(RightSquareBracket) && !self.at_eof() {
44 self.next();
45 }
46 self.advance_if(RightSquareBracket);
47 return None;
48 }
49
50 let name = self.read_identifier();
51 let args = if self.advance_if(LeftParen) {
52 self.parse_attribute_args()
53 } else {
54 vec![]
55 };
56
57 if !self.advance_if(RightSquareBracket) {
58 self.track_error("expected `]`", "Add `]` to close the attribute");
59 }
60
61 Some(Attribute {
62 name: name.to_string(),
63 args,
64 span: self.span_from_tokens(start),
65 })
66 }
67
68 fn parse_attribute_args(&mut self) -> Vec<AttributeArg> {
69 let mut args = vec![];
70
71 while self.is_not(RightParen) && self.is_not(RightSquareBracket) && !self.at_eof() {
72 if let Some(arg) = self.parse_attribute_arg() {
73 args.push(arg);
74 } else {
75 while !self.at_sync_point() && !self.at_eof() {
76 self.next();
77 }
78 }
79
80 if !self.advance_if(Comma) {
81 break;
82 }
83 }
84
85 if !self.advance_if(RightParen) {
86 self.track_error("expected `)`", "Add `)` to close the attribute arguments");
87 }
88 args
89 }
90
91 fn parse_attribute_arg(&mut self) -> Option<AttributeArg> {
92 if self.advance_if(Bang) {
93 if self.is(Identifier) {
94 return Some(AttributeArg::NegatedFlag(
95 self.read_identifier().to_string(),
96 ));
97 } else {
98 self.track_error(
99 "expected identifier after `!`",
100 "Add an identifier like `omitempty` after `!`",
101 );
102 return None;
103 }
104 }
105
106 if self.is(Identifier) {
107 return Some(AttributeArg::Flag(self.read_identifier().to_string()));
108 }
109
110 if self.is(String) {
111 let token = self.current_token();
112 self.next();
113 let text = token.text;
114 let value = if text.len() >= 2 {
115 &text[1..text.len() - 1]
116 } else {
117 text
118 };
119 return Some(AttributeArg::String(value.to_string()));
120 }
121
122 if self.is(Backtick) {
123 let token = self.current_token();
124 self.next();
125 let text = token.text;
126 let value = if text.len() >= 2 {
127 &text[1..text.len() - 1]
128 } else {
129 text
130 };
131 return Some(AttributeArg::Raw(value.to_string()));
132 }
133
134 self.track_error(
135 "expected attribute argument",
136 "Add a flag (e.g. `omitempty`), string (e.g. `\"name\"`), or raw tag (e.g. `` `json:\"name\"` ``)",
137 );
138 None
139 }
140
141 pub fn parse_enum_definition(
142 &mut self,
143 doc: Option<std::string::String>,
144 attributes: Vec<Attribute>,
145 ) -> Expression {
146 let start = self.current_token();
147
148 self.ensure(Enum);
149
150 let name_token = self.current_token();
151 let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
152 let name = self.read_identifier();
153 let generics = self.parse_generics();
154
155 let underlying_start = self.current_token();
156 if self.advance_if(Colon) {
157 let _ = self.parse_annotation();
158 let underlying_span = Span::new(
159 self.file_id,
160 underlying_start.byte_offset,
161 underlying_start.byte_length,
162 );
163 let error = ParseError::new(
164 "Enum with underlying type",
165 underlying_span,
166 "enums cannot have an underlying type",
167 )
168 .with_parse_code("enum_underlying_type")
169 .with_help(
170 "Remove the `: type` annotation. To model a Go defined primitive type, use a named primitive type such as `pub struct Weekday(int)` with package-level constants.",
171 );
172 self.errors.push(error);
173 }
174
175 self.ensure(LeftCurlyBrace);
176
177 self.parse_regular_enum_body(doc, attributes, name, name_span, generics, start)
178 }
179
180 fn parse_regular_enum_body(
181 &mut self,
182 doc: Option<std::string::String>,
183 attributes: Vec<Attribute>,
184 name: EcoString,
185 name_span: Span,
186 generics: Vec<Generic>,
187 start: Token<'source>,
188 ) -> Expression {
189 let mut variants = vec![];
190 let mut seen_variants: Vec<(EcoString, Span)> = vec![];
191
192 while self.is_not(RightCurlyBrace) {
193 let start_position = self.stream.position;
194
195 let variant_doc = self.collect_doc_comments().map(|(text, _)| text);
196 if let Some(variant) = self.parse_enum_variant_with_doc(variant_doc) {
197 if let Some((_, first_span)) =
198 seen_variants.iter().find(|(n, _)| n == &variant.name)
199 {
200 self.error_duplicate_enum_variant(
201 &variant.name,
202 *first_span,
203 variant.name_span,
204 );
205 } else {
206 seen_variants.push((variant.name.clone(), variant.name_span));
207 }
208 variants.push(variant);
209 }
210 self.expect_comma_or(RightCurlyBrace);
211 self.ensure_progress(start_position, RightCurlyBrace);
212 }
213
214 self.ensure(RightCurlyBrace);
215
216 Expression::Enum {
217 doc,
218 attributes,
219 name,
220 name_span,
221 generics,
222 variants,
223 visibility: Visibility::Private,
224 span: self.span_from_tokens(start),
225 }
226 }
227
228 fn parse_enum_variant_with_doc(
229 &mut self,
230 doc: Option<std::string::String>,
231 ) -> Option<EnumVariant> {
232 if self.is_not(Identifier) {
233 self.track_error(
234 "expected variant name",
235 "Variant names must be identifiers.",
236 );
237 return None;
238 }
239
240 let name_token = self.current_token();
241 let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
242 let name = self.read_identifier();
243
244 if self.is(Equal) {
245 let eq_token = self.current_token();
246 let eq_span = Span::new(self.file_id, eq_token.byte_offset, eq_token.byte_length);
247 let error = ParseError::new(
248 "Assigned enum variant",
249 eq_span,
250 "enum variants cannot have assigned values",
251 )
252 .with_parse_code("enum_assigned_variant")
253 .with_help(
254 "Lisette enums are sum types, not Go const groups. To model a Go defined primitive type, use a named primitive type such as `pub struct Weekday(int)` with package-level constants.",
255 );
256 self.errors.push(error);
257 self.next(); self.skip_assigned_variant_value();
259 }
260
261 let fields = self.parse_enum_variant_fields();
262
263 Some(EnumVariant {
264 doc,
265 name,
266 name_span,
267 fields,
268 })
269 }
270
271 fn skip_assigned_variant_value(&mut self) {
272 self.advance_if(Minus);
273 if self.is(Integer) || self.is(String) {
274 self.next();
275 }
276 }
277
278 fn parse_enum_variant_fields(&mut self) -> VariantFields {
279 if self.advance_if(LeftParen) {
280 return self.parse_tuple_variant_fields();
281 }
282
283 if self.advance_if(LeftCurlyBrace) {
284 return self.parse_struct_variant_fields();
285 }
286
287 VariantFields::Unit
288 }
289
290 fn parse_tuple_variant_fields(&mut self) -> VariantFields {
291 let mut fields = vec![];
292
293 loop {
294 if self.at_eof()
295 || self.is(RightParen)
296 || self.is(RightCurlyBrace)
297 || !self.can_start_annotation()
298 {
299 break;
300 }
301
302 let field = EnumFieldDefinition {
303 name: format!("field{}", fields.len()).into(),
304 name_span: Span::dummy(),
305 annotation: self.parse_annotation(),
306 ty: Type::uninferred(),
307 };
308
309 fields.push(field);
310
311 self.expect_comma_or(RightParen);
312 }
313
314 self.ensure(RightParen);
315
316 VariantFields::Tuple(fields)
317 }
318
319 fn parse_struct_variant_fields(&mut self) -> VariantFields {
320 let mut fields = vec![];
321 let mut seen_fields: Vec<(EcoString, Span)> = vec![];
322
323 loop {
324 if self.at_eof()
325 || self.is(RightCurlyBrace)
326 || self.at_item_boundary()
327 || self.is_not(Identifier)
328 {
329 break;
330 }
331
332 let name_token = self.current_token();
333 let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
334 let name = self.read_identifier();
335 self.ensure(Colon);
336 let annotation = self.parse_annotation();
337
338 if let Some((_, first_span)) = seen_fields.iter().find(|(n, _)| n == &name) {
339 self.error_duplicate_struct_field(&name, *first_span, name_span);
340 } else {
341 seen_fields.push((name.clone(), name_span));
342 }
343
344 let field = EnumFieldDefinition {
345 name,
346 name_span,
347 annotation,
348 ty: Type::uninferred(),
349 };
350
351 fields.push(field);
352
353 self.expect_comma_or(RightCurlyBrace);
354 }
355
356 self.ensure(RightCurlyBrace);
357
358 VariantFields::Struct(fields)
359 }
360
361 pub fn parse_struct_definition(
362 &mut self,
363 doc: Option<std::string::String>,
364 attributes: Vec<Attribute>,
365 ) -> Expression {
366 let start = self.current_token();
367
368 self.ensure(Struct);
369
370 let name_token = self.current_token();
371 let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
372 let name = self.read_identifier();
373 let generics = self.parse_generics();
374
375 if self.is(LeftParen) {
376 return self.parse_tuple_struct(doc, attributes, name, name_span, generics, start);
377 }
378
379 self.parse_named_struct(doc, attributes, name, name_span, generics, start)
380 }
381
382 fn parse_named_struct(
383 &mut self,
384 doc: Option<std::string::String>,
385 attributes: Vec<Attribute>,
386 name: EcoString,
387 name_span: Span,
388 generics: Vec<Generic>,
389 start: Token<'source>,
390 ) -> Expression {
391 let mut fields = vec![];
392 let mut seen_fields: Vec<(EcoString, Span)> = vec![];
393
394 self.ensure(LeftCurlyBrace);
395
396 while self.is_not(RightCurlyBrace) {
397 let start_position = self.stream.position;
398
399 let field_attributes = self.parse_attributes();
400 let field_doc = self.collect_doc_comments().map(|(text, _)| text);
401 if let Some(field) = self.parse_struct_field_with_doc(field_doc, field_attributes) {
402 if let Some((_, first_span)) = seen_fields.iter().find(|(n, _)| n == &field.name) {
403 self.error_duplicate_struct_field(&field.name, *first_span, field.name_span);
404 } else {
405 seen_fields.push((field.name.clone(), field.name_span));
406 }
407 fields.push(field);
408 }
409 self.expect_comma_or(RightCurlyBrace);
410 self.ensure_progress(start_position, RightCurlyBrace);
411 }
412
413 self.ensure(RightCurlyBrace);
414
415 Expression::Struct {
416 doc,
417 attributes,
418 name,
419 name_span,
420 generics,
421 fields,
422 kind: StructKind::Record,
423 visibility: Visibility::Private,
424 span: self.span_from_tokens(start),
425 }
426 }
427
428 fn parse_tuple_struct(
429 &mut self,
430 doc: Option<std::string::String>,
431 attributes: Vec<Attribute>,
432 name: EcoString,
433 name_span: Span,
434 generics: Vec<Generic>,
435 start: Token<'source>,
436 ) -> Expression {
437 self.ensure(LeftParen);
438
439 let mut fields = vec![];
440 let mut index = 0;
441
442 while self.is_not(RightParen) {
443 if self.at_eof() || self.at_item_boundary() || !self.can_start_annotation() {
444 break;
445 }
446
447 let field_start = self.current_token();
448 let annotation = self.parse_annotation();
449 let field_span = self.span_from_tokens(field_start);
450
451 fields.push(StructFieldDefinition {
452 doc: None,
453 attributes: vec![],
454 name: format!("_{}", index).into(),
455 name_span: field_span,
456 annotation,
457 visibility: Visibility::Private,
458 ty: Type::uninferred(),
459 embedded: false,
460 });
461
462 index += 1;
463 self.expect_comma_or(RightParen);
464 }
465
466 self.ensure(RightParen);
467
468 Expression::Struct {
469 doc,
470 attributes,
471 name,
472 name_span,
473 generics,
474 fields,
475 kind: StructKind::Tuple,
476 visibility: Visibility::Private,
477 span: self.span_from_tokens(start),
478 }
479 }
480
481 fn parse_struct_field_with_doc(
482 &mut self,
483 doc: Option<std::string::String>,
484 attributes: Vec<Attribute>,
485 ) -> Option<StructFieldDefinition> {
486 let visibility = if self.advance_if(Pub) {
487 Visibility::Public
488 } else {
489 Visibility::Private
490 };
491
492 if self.is(Mut) {
493 self.track_error(
494 "fields cannot be marked `mut`",
495 "Fields cannot be marked `mut`; mutability applies to bindings (`let mut x = ...`).",
496 );
497 self.next();
498 }
499
500 if self.is(Identifier)
502 && self.current_token().text == "embed"
503 && self.stream.peek_ahead(1).kind != Colon
504 {
505 if visibility.is_public() {
506 self.track_error(
507 "embedded field cannot be `pub`",
508 "An embedded field takes no `pub`; its visibility derives from the embedded type.",
509 );
510 }
511 return self.parse_embedded_field(doc, attributes);
512 }
513
514 if self.is_not(Identifier) {
515 self.track_error("expected field name", "Field names must be identifiers.");
516 return None;
517 }
518
519 let name_token = self.current_token();
520 let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
521 let name = self.read_identifier();
522
523 self.ensure(Colon);
524
525 Some(StructFieldDefinition {
526 doc,
527 attributes,
528 visibility,
529 name,
530 name_span,
531 annotation: self.parse_annotation(),
532 ty: Type::uninferred(),
533 embedded: false,
534 })
535 }
536
537 fn parse_embedded_field(
538 &mut self,
539 doc: Option<std::string::String>,
540 attributes: Vec<Attribute>,
541 ) -> Option<StructFieldDefinition> {
542 let start = self.current_token();
543 self.ensure(Identifier);
544
545 let annotation = self.parse_annotation();
546 let span = self.span_from_tokens(start);
547
548 let Some(name) = Self::embedded_field_name(&annotation) else {
549 self.track_error_at(
550 span,
551 "expected a named type after `embed`",
552 "`embed` requires a named type; a function or tuple type cannot be embedded.",
553 );
554 return None;
555 };
556
557 if let Some(attribute) = attributes.first() {
558 self.track_error_at(
559 attribute.span,
560 "embedded field cannot have attributes",
561 "An embedded field takes no attributes; its serialization follows Go's anonymous-field inlining.",
562 );
563 }
564
565 Some(StructFieldDefinition {
566 doc,
567 attributes: vec![],
568 visibility: Visibility::Private,
569 name,
570 name_span: span,
571 annotation,
572 ty: Type::uninferred(),
573 embedded: true,
574 })
575 }
576
577 fn embedded_field_name(annotation: &Annotation) -> Option<EcoString> {
578 let mut current = annotation;
579 loop {
580 let Annotation::Constructor { name, params, .. } = current else {
581 return None;
582 };
583 let segment = name.rsplit('.').next().unwrap_or(name);
584 if (segment == "Option" || segment == "Ref") && params.len() == 1 {
585 current = ¶ms[0];
586 continue;
587 }
588 return Some(segment.into());
589 }
590 }
591
592 pub fn parse_const_definition(&mut self, doc: Option<std::string::String>) -> Expression {
593 let start = self.current_token();
594
595 self.ensure(Const);
596
597 let identifier_token = self.current_token();
598 let identifier_span = Span::new(
599 self.file_id,
600 identifier_token.byte_offset,
601 identifier_token.byte_length,
602 );
603 let identifier = self.read_identifier();
604 let annotation = if self.advance_if(Colon) {
605 Some(self.parse_annotation())
606 } else {
607 None
608 };
609
610 let expression = if self.advance_if(Equal) {
611 self.parse_expression()
612 } else {
613 Expression::NoOp
614 };
615
616 Expression::Const {
617 doc,
618 identifier,
619 identifier_span,
620 annotation,
621 expression: expression.into(),
622 visibility: Visibility::Private,
623 ty: Type::uninferred(),
624 span: self.span_from_tokens(start),
625 }
626 }
627
628 pub fn parse_var_declaration(&mut self, doc: Option<std::string::String>) -> Expression {
629 let start = self.current_token();
630
631 self.ensure(Var);
632
633 let name_token = self.current_token();
634 let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
635 let name = self.read_identifier();
636
637 if self.advance_if(Equal) {
638 return self.recover_var_initializer(start);
639 }
640
641 self.ensure(Colon);
642 let annotation = self.parse_annotation();
643
644 if self.advance_if(Equal) {
645 return self.recover_var_initializer(start);
646 }
647
648 Expression::VariableDeclaration {
649 doc,
650 name,
651 name_span,
652 annotation,
653 visibility: Visibility::Private,
654 ty: Type::uninferred(),
655 span: self.span_from_tokens(start),
656 }
657 }
658
659 fn recover_var_initializer(&mut self, start: Token<'source>) -> Expression {
660 self.parse_expression();
661 self.error_var_initializer(self.span_from_token(start));
662
663 Expression::Unit {
664 ty: Type::uninferred(),
665 span: self.span_from_tokens(start),
666 }
667 }
668
669 pub fn parse_impl_block(&mut self) -> Expression {
670 let start = self.current_token();
671
672 self.ensure(Impl);
673
674 let generics = self.parse_generics();
675
676 let receiver = self.parse_annotation(); let (receiver_name, annotation) = match &receiver {
679 Annotation::Constructor { name, .. } => (name.clone(), receiver),
680 _ => {
681 self.track_error("expected `impl` receiver", "Use `impl TypeName { ... }`.");
682 ("".into(), Annotation::Unknown)
683 }
684 };
685
686 if self.is(For) {
687 self.track_error(
688 "invalid syntax",
689 "Lisette types satisfy interfaces automatically by having the required methods. Use `impl Type { ... }` to add methods.",
690 );
691 self.next();
692 self.parse_annotation();
693 }
694
695 let mut methods = vec![];
696
697 self.ensure(LeftCurlyBrace);
698
699 while self.is_not(RightCurlyBrace) {
700 self.advance_if(Semicolon);
701 if self.is(RightCurlyBrace) {
702 break;
703 }
704
705 let method_doc = self.collect_doc_comments();
706 let method_attrs = self.parse_attributes();
707 let is_public = self.advance_if(Pub);
708
709 if self.is(Function) {
710 let method = self.parse_function(
711 method_doc.map(|(text, _)| text),
712 method_attrs,
713 ParamMode::Strict,
714 );
715 let method = if is_public {
716 method.set_public()
717 } else {
718 method
719 };
720 methods.push(method);
721 } else {
722 if let Some((_, span)) = method_doc {
723 self.error_detached_doc_comment(span);
724 }
725 self.track_error(
726 "expected `fn` in impl block",
727 "Only functions are allowed in `impl` blocks.",
728 );
729 self.next();
730 }
731 }
732
733 self.ensure(RightCurlyBrace);
734
735 Expression::ImplBlock {
736 annotation,
737 methods,
738 receiver_name,
739 generics,
740 ty: Type::uninferred(),
741 span: self.span_from_tokens(start),
742 }
743 }
744
745 pub fn parse_interface_definition(&mut self, doc: Option<std::string::String>) -> Expression {
746 let start = self.current_token();
747
748 self.ensure(Interface);
749
750 let name_token = self.current_token();
751 let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
752 let name = self.read_identifier();
753
754 let generics = self.parse_generics();
755
756 let mut parents = vec![];
757 let mut seen_parents: Vec<(EcoString, Span)> = vec![];
758 let mut method_signatures = vec![];
759 let mut seen_methods: Vec<(EcoString, Span)> = vec![];
760
761 self.ensure(LeftCurlyBrace);
762
763 while self.is_not(RightCurlyBrace) {
764 self.advance_if(Semicolon);
765 if self.is(RightCurlyBrace) {
766 break;
767 }
768
769 let item_doc = self.collect_doc_comments();
770 let method_attrs = self.parse_attributes();
771 if !self.is(Function)
772 && let Some(attribute) = method_attrs.first()
773 {
774 self.error_misplaced_attribute(attribute.span);
775 }
776 match self.current_token().kind {
777 Function => {
778 let method =
779 self.parse_interface_method(item_doc.map(|(text, _)| text), method_attrs);
780 if let Expression::Function {
781 ref name,
782 ref name_span,
783 ..
784 } = method
785 {
786 if let Some((_, first_span)) = seen_methods.iter().find(|(n, _)| n == name)
787 {
788 self.error_duplicate_interface_method(name, *first_span, *name_span);
789 } else {
790 seen_methods.push((name.clone(), *name_span));
791 }
792 }
793 method_signatures.push(method);
794 self.advance_if(Semicolon);
795 }
796
797 Impl => {
798 let keyword = self.current_token();
799 let keyword_span =
800 Span::new(self.file_id, keyword.byte_offset, keyword.byte_length);
801 self.ensure(Impl);
802 self.error_impl_interface_embed(keyword_span);
803 self.parse_interface_parent(item_doc, &mut seen_parents, &mut parents);
804 }
805
806 Identifier if self.current_token().text == "embed" => {
807 self.next();
808 self.parse_interface_parent(item_doc, &mut seen_parents, &mut parents);
809 }
810
811 _ => {
812 if let Some((_, span)) = item_doc {
813 self.error_detached_doc_comment(span);
814 }
815 self.track_error(
816 "expected `fn` or `embed`",
817 "Only method signatures (`fn`) and embeddings (`embed`) are allowed in interfaces.",
818 );
819 self.next();
820 }
821 }
822 }
823
824 self.ensure(RightCurlyBrace);
825
826 Expression::Interface {
827 doc,
828 name,
829 name_span,
830 generics,
831 parents,
832 method_signatures,
833 visibility: Visibility::Private,
834 span: self.span_from_tokens(start),
835 }
836 }
837
838 fn parse_interface_parent(
839 &mut self,
840 item_doc: Option<(std::string::String, Span)>,
841 seen_parents: &mut Vec<(EcoString, Span)>,
842 parents: &mut Vec<ParentInterface>,
843 ) {
844 if let Some((_, span)) = item_doc {
845 self.error_detached_doc_comment(span);
846 }
847
848 let parent_start = self.current_token();
849 let annotation = self.parse_annotation();
850 let parent_span = self.span_from_tokens(parent_start);
851
852 if let Annotation::Constructor { name, .. } = &annotation {
853 if let Some((_, first_span)) = seen_parents.iter().find(|(n, _)| n == name.as_str()) {
854 self.error_duplicate_embed_parent(*first_span, parent_span);
855 } else {
856 seen_parents.push((name.clone(), parent_span));
857 }
858 }
859
860 parents.push(ParentInterface {
861 annotation,
862 ty: Type::uninferred(),
863 span: parent_span,
864 });
865 self.advance_if(Semicolon);
866 }
867}