1pub mod prelude;
6
7use std::fmt;
8use std::fmt::{Debug, Formatter};
9use std::hash::Hash;
10
11#[derive(PartialEq, Eq, Hash, Default, Clone)]
12pub struct SpanWithoutFileId {
13 pub offset: u32,
14 pub length: u16,
15}
16
17impl Debug for SpanWithoutFileId {
18 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
19 write!(f, "<{}:{}>", self.offset, self.length)
20 }
21}
22
23#[derive(PartialEq, Eq, Hash, Default, Clone)]
25pub struct Node {
26 pub span: SpanWithoutFileId,
27 }
29
30impl Debug for Node {
31 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
32 write!(f, "{:?}", self.span)
33 }
34}
35
36#[derive(Debug, PartialEq, Eq, Clone, Hash)]
38pub struct QualifiedTypeIdentifier {
39 pub name: LocalTypeIdentifier,
40 pub module_path: Option<ModulePath>,
41 pub generic_params: Vec<GenericParameter>,
42}
43
44impl QualifiedTypeIdentifier {
45 #[must_use]
46 pub fn new(name: LocalTypeIdentifier, module_path: Vec<Node>) -> Self {
47 let module_path = if module_path.is_empty() {
48 None
49 } else {
50 Some(ModulePath(module_path))
51 };
52
53 Self {
54 name,
55 module_path,
56 generic_params: Vec::new(),
57 }
58 }
59
60 #[must_use]
61 pub fn new_with_generics(
62 name: LocalTypeIdentifier,
63 module_path: Vec<Node>,
64 generic_params: Vec<GenericParameter>,
65 ) -> Self {
66 let module_path = if module_path.is_empty() {
67 None
68 } else {
69 Some(ModulePath(module_path))
70 };
71
72 Self {
73 name,
74 module_path,
75 generic_params,
76 }
77 }
78}
79
80#[derive(Debug, PartialEq, Eq, Hash, Clone)]
81pub struct QualifiedIdentifier {
82 pub name: Node,
83 pub module_path: Option<ModulePath>,
84 pub generic_params: Vec<GenericParameter>,
85}
86
87impl QualifiedIdentifier {
88 #[must_use]
89 pub fn new(name: Node, module_path: Vec<Node>) -> Self {
90 let module_path = if module_path.is_empty() {
91 None
92 } else {
93 Some(ModulePath(module_path))
94 };
95
96 Self {
97 name,
98 module_path,
99 generic_params: vec![],
100 }
101 }
102
103 #[must_use]
104 pub fn new_with_generics(
105 name: Node,
106 module_path: Vec<Node>,
107 generic_params: Vec<GenericParameter>,
108 ) -> Self {
109 let module_path = if module_path.is_empty() {
110 None
111 } else {
112 Some(ModulePath(module_path))
113 };
114
115 Self {
116 name,
117 module_path,
118 generic_params,
119 }
120 }
121}
122
123#[derive(Debug, PartialEq, Eq, Hash, Default, Clone)]
124pub struct LocalTypeIdentifier(pub Node);
125
126impl LocalTypeIdentifier {
127 #[must_use]
128 pub const fn new(node: Node) -> Self {
129 Self(node)
130 }
131}
132
133#[derive(Debug, PartialEq, Eq, Hash, Default, Clone)]
134pub struct TypeVariable(pub Node);
135
136#[derive(Debug, PartialEq, Eq, Hash, Default, Clone)]
137pub struct LocalTypeIdentifierWithOptionalTypeVariables {
138 pub name: Node,
139 pub type_variables: Vec<TypeVariable>,
140}
141
142#[derive(PartialEq, Eq, Hash, Debug, Clone)]
143pub struct LocalIdentifier(pub Node);
144
145impl LocalIdentifier {
146 #[must_use]
147 pub const fn new(node: Node) -> Self {
148 Self(node)
149 }
150}
151
152#[derive(Debug, PartialEq, Eq, Hash, Default, Clone)]
153pub struct LocalConstantIdentifier(pub Node);
154
155#[derive(Debug, PartialEq, Eq, Clone, Hash)]
156pub struct QualifiedConstantIdentifier {
157 pub name: Node,
158 pub module_path: Option<ModulePath>,
159}
160
161impl QualifiedConstantIdentifier {
162 #[must_use]
163 pub const fn new(name: Node, module_path: Option<ModulePath>) -> Self {
164 Self { name, module_path }
165 }
166}
167
168#[derive(Debug, Eq, Hash, Clone, PartialEq)]
169pub struct FieldName(pub Node);
170
171#[derive(Debug, Eq, Hash, PartialEq, Clone)]
172pub struct ModulePath(pub Vec<Node>);
173
174impl Default for ModulePath {
175 fn default() -> Self {
176 Self::new()
177 }
178}
179
180impl ModulePath {
181 #[must_use]
182 pub const fn new() -> Self {
183 Self(vec![])
184 }
185}
186
187#[derive(Debug, Clone)]
188pub enum ImportItem {
189 Identifier(LocalIdentifier),
190 Type(LocalTypeIdentifier),
191}
192
193#[derive(Debug, Clone)]
194pub enum ImportItems {
195 Nothing,
196 Items(Vec<ImportItem>),
197 All,
198}
199
200#[derive(Debug, Clone)]
201pub struct Mod {
202 pub module_path: ModulePath,
203 pub items: ImportItems,
204}
205
206#[derive(Debug, Clone)]
207pub struct Use {
208 pub module_path: ModulePath,
209 pub items: ImportItems,
210}
211
212#[derive(Debug, Eq, Clone, PartialEq)]
213pub struct AliasType {
214 pub identifier: LocalTypeIdentifier,
215 pub referenced_type: Type,
216}
217
218#[derive(Debug, Eq, PartialEq, Hash, Clone, Default)]
219pub struct AnonymousStructType {
220 pub fields: Vec<StructTypeField>,
221}
222
223impl AnonymousStructType {
224 #[must_use]
225 pub const fn new(fields: Vec<StructTypeField>) -> Self {
226 Self { fields }
227 }
228}
229
230#[derive(Debug, Clone)]
231pub struct ConstantInfo {
232 pub constant_identifier: LocalConstantIdentifier,
233 pub annotation: Option<Type>,
234 pub expression: Box<Expression>,
235}
236
237#[derive(Debug, Clone)]
238pub struct NamedStructDef {
239 pub identifier: LocalTypeIdentifierWithOptionalTypeVariables,
240 pub struct_type: AnonymousStructType,
241}
242
243#[derive(Debug, Clone)]
244pub enum DefinitionKind {
245 AliasDef(AliasType),
246 NamedStructDef(NamedStructDef),
247 EnumDef(
248 LocalTypeIdentifierWithOptionalTypeVariables,
249 Vec<EnumVariantType>,
250 ),
251 FunctionDef(Function),
252 ImplDef(LocalTypeIdentifierWithOptionalTypeVariables, Vec<Function>),
253 Mod(Mod),
254 Use(Use),
255 Constant(ConstantInfo),
257}
258
259#[derive(Debug, Clone)]
260pub struct Definition {
261 pub node: Node,
262 pub kind: DefinitionKind,
263 pub attributes: Vec<Attribute>,
264}
265
266#[derive(Debug, Clone)]
267pub struct ForVar {
268 pub identifier: Node,
269 pub is_mut: Option<Node>,
270}
271
272#[derive(Debug, Clone)]
273pub enum ForPattern {
274 Single(ForVar),
275 Pair(ForVar, ForVar),
276}
277
278impl ForPattern {
279 #[must_use]
280 pub const fn is_key_variable_mut(&self) -> bool {
281 match self {
282 Self::Single(_a) => false,
283 Self::Pair(a, _b) => a.is_mut.is_some(),
284 }
285 }
286 #[must_use]
287 pub fn is_value_mut(&self) -> Option<Node> {
288 match self {
289 Self::Single(a) => a.is_mut.clone(),
290 Self::Pair(a, b) => {
291 assert!(
292 a.is_mut.is_none(),
293 "key target var is not allowed to be mut"
294 );
295 b.is_mut.clone()
296 }
297 }
298 }
299}
300
301#[derive(Debug, Clone)]
302pub struct IterableExpression {
303 pub expression: Box<Expression>,
304}
305
306#[derive(Clone, Eq, PartialEq)]
307pub struct Variable {
308 pub name: Node,
309 pub is_mutable: Option<Node>,
310}
311
312#[derive(Debug, Clone)]
313pub struct VariableBinding {
314 pub variable: Variable,
315 pub expression: Option<Expression>,
316}
317
318impl Variable {
319 #[must_use]
320 pub const fn new(name: Node, is_mutable: Option<Node>) -> Self {
321 Self { name, is_mutable }
322 }
323}
324
325impl Debug for Variable {
328 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
329 if let Some(found) = &self.is_mutable {
330 write!(f, "mut {found:?} {:?}", self.name)
331 } else {
332 write!(f, "{:?}", self.name)
333 }
334 }
335}
336
337#[derive(Debug, Eq, Clone, PartialEq)]
338pub struct Parameter {
339 pub variable: Variable,
340 pub param_type: Type,
341}
342
343#[derive(Debug, Clone)]
344pub struct FunctionDeclaration {
345 pub name: Node,
346 pub params: Vec<Parameter>,
347 pub self_parameter: Option<SelfParameter>,
348 pub return_type: Option<Type>,
349}
350
351#[derive(Debug, Clone)]
352pub struct FunctionWithBody {
353 pub attributes: Vec<Attribute>,
354 pub declaration: FunctionDeclaration,
355 pub body: Expression,
356}
357
358#[derive(Debug, Clone)]
359pub enum Function {
360 Internal(FunctionWithBody),
361 External(Node, FunctionDeclaration),
362}
363
364impl Function {
365 #[must_use]
366 pub const fn node(&self) -> &Node {
367 match self {
368 Self::Internal(func_with_body) => &func_with_body.body.node,
369 Self::External(node, _) => node,
370 }
371 }
372}
373
374#[derive(Debug, Clone)]
375pub struct SelfParameter {
376 pub is_mutable: Option<Node>,
377 pub self_node: Node,
378}
379
380#[derive(Debug, PartialEq, Eq)]
381pub enum AssignmentOperatorKind {
382 Compound(CompoundOperatorKind),
383 Assign, }
385
386#[derive(Debug, PartialEq, Eq, Clone)]
387pub enum CompoundOperatorKind {
388 Add, Sub, Mul, Div, Modulo, }
394
395#[derive(Debug, Clone)]
396pub struct CompoundOperator {
397 pub node: Node,
398 pub kind: CompoundOperatorKind,
399}
400
401#[derive(Debug, Clone)]
402pub enum RangeMode {
403 Inclusive,
404 Exclusive,
405}
406
407#[derive(Clone)]
408pub struct Expression {
409 pub kind: ExpressionKind,
410 pub node: Node,
411}
412
413impl Debug for Expression {
414 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
415 write!(f, "{:?}{:?}", self.node.span, self.kind)
416 }
417}
418
419#[derive(Debug, Clone)]
420pub enum Postfix {
421 FieldAccess(Node),
422 Subscript(Expression),
423 MemberCall(Node, Option<Vec<GenericParameter>>, Vec<Expression>),
424 FunctionCall(Node, Option<Vec<GenericParameter>>, Vec<Expression>),
425 OptionalChainingOperator(Node), SubscriptTuple(Expression, Expression),
427}
428
429#[derive(Debug, Clone)]
430pub struct PostfixChain {
431 pub base: Box<Expression>,
432 pub postfixes: Vec<Postfix>,
433}
434
435#[derive(Debug, Clone)]
436pub enum ExpressionKind {
437 PostfixChain(PostfixChain),
439
440 ContextAccess, VariableReference(Variable),
443 ConstantReference(QualifiedConstantIdentifier),
444 StaticMemberFunctionReference(QualifiedTypeIdentifier, Node),
445 IdentifierReference(QualifiedIdentifier),
446
447 VariableDefinition(Variable, Option<Type>, Box<Expression>),
449 VariableAssignment(Variable, Box<Expression>),
450 Assignment(Box<Expression>, Box<Expression>),
451 CompoundAssignment(Box<Expression>, CompoundOperator, Box<Expression>),
452 DestructuringAssignment(Vec<Variable>, Box<Expression>),
453
454 BinaryOp(Box<Expression>, BinaryOperator, Box<Expression>),
456 UnaryOp(UnaryOperator, Box<Expression>),
457
458 Block(Vec<Expression>),
460 With(Vec<VariableBinding>, Box<Expression>),
461 When(
462 Vec<VariableBinding>,
463 Box<Expression>,
464 Option<Box<Expression>>,
465 ),
466
467 ForLoop(ForPattern, IterableExpression, Box<Expression>),
469 WhileLoop(Box<Expression>, Box<Expression>),
470
471 If(Box<Expression>, Box<Expression>, Option<Box<Expression>>),
473 Match(Box<Expression>, Vec<MatchArm>),
474 Guard(Vec<GuardExpr>),
475
476 InterpolatedString(Vec<StringPart>),
477
478 AnonymousStructLiteral(Vec<FieldExpression>, bool),
480 NamedStructLiteral(QualifiedTypeIdentifier, Vec<FieldExpression>, bool),
481 Range(Box<Expression>, Box<Expression>, RangeMode),
482 Literal(LiteralKind),
483
484 Lambda(Vec<Variable>, Box<Expression>),
485 Error, }
487
488#[derive(Debug, Clone)]
489pub struct MatchArm {
490 pub pattern: Pattern,
491 pub expression: Expression,
492}
493
494#[derive(Debug, Clone)]
496pub enum LiteralKind {
497 Int,
498 Float,
499 Byte,
500 String(String),
501 Bool,
502 EnumVariant(EnumVariantLiteral),
503 Tuple(Vec<Expression>),
504 InternalInitializerList(Vec<Expression>),
505 InternalInitializerPairList(Vec<(Expression, Expression)>),
506 None,
507}
508
509#[derive(Debug, Clone)]
510pub struct FieldExpression {
511 pub field_name: FieldName,
512 pub expression: Expression,
513}
514
515#[derive(Debug, Eq, Hash, Clone, PartialEq)]
516pub struct StructTypeField {
517 pub field_name: FieldName,
518 pub field_type: Type,
519}
520
521#[derive(Clone, Debug)]
522pub struct EnumVariantLiteral {
523 pub qualified_enum_type_name: Option<QualifiedTypeIdentifier>,
524 pub name: LocalTypeIdentifier,
525 pub kind: EnumVariantLiteralKind,
526}
527
528#[derive(Debug, Clone)]
529pub enum EnumVariantLiteralKind {
530 Simple,
531 Tuple(Vec<Expression>),
532 Struct(Vec<FieldExpression>, bool),
533}
534
535#[derive(Debug, Clone)]
536pub enum EnumVariantType {
537 Simple(Node),
538 Direct(Node, Type),
539 Tuple(Node, Vec<Type>),
540 Struct(Node, AnonymousStructType),
541}
542
543#[derive(Debug, PartialEq, Eq, Clone, Hash)]
544pub struct TypeForParameter {
545 pub ast_type: Type,
546 pub is_mutable: bool,
547}
548
549#[derive(Debug, Clone, PartialEq, Eq, Hash)]
550pub enum GenericParameter {
551 Type(Type),
552 UnsignedInt(Node),
553 UnsignedTupleInt(Node, Node),
554}
555
556impl GenericParameter {
557 #[must_use]
558 pub fn get_unsigned_int_node(&self) -> &Node {
559 let Self::UnsignedInt(node) = self else {
560 panic!("wasn't unsigned int")
561 };
562 node
563 }
564
565 #[must_use]
566 pub fn get_unsigned_int_tuple_nodes(&self) -> (&Node, &Node) {
567 let Self::UnsignedTupleInt(first, second) = self else {
568 panic!("wasn't unsigned int tuple")
569 };
570 (first, second)
571 }
572}
573
574impl GenericParameter {
575 #[must_use]
576 pub fn get_type(&self) -> &Type {
577 let Self::Type(ty) = self else {
578 panic!("{}", format!("wasn't type {self:?}"))
579 };
580 ty
581 }
582}
583
584#[derive(Debug, PartialEq, Eq, Clone, Hash)]
585pub enum Type {
586 FixedCapacityArray(Box<Type>, Node), Slice(Box<Type>), FixedCapacityMap(Box<Type>, Box<Type>, Node), DynamicLengthMap(Box<Type>, Box<Type>), AnonymousStruct(AnonymousStructType),
593 Unit,
594 Tuple(Vec<Type>),
595 Function(Vec<TypeForParameter>, Box<Type>),
596
597 Named(QualifiedTypeIdentifier),
598
599 Optional(Box<Type>, Node),
600 Never,
601}
602
603#[derive(Debug, Clone)]
604pub struct BinaryOperator {
605 pub kind: BinaryOperatorKind,
606 pub node: Node,
607}
608
609#[derive(Debug, Clone, PartialEq, Eq)]
611pub enum BinaryOperatorKind {
612 Add,
613 Subtract,
614 Multiply,
615 Divide,
616 Modulo,
617 LogicalOr,
618 LogicalAnd,
619 Equal,
620 NotEqual,
621 LessThan,
622 LessEqual,
623 GreaterThan,
624 GreaterEqual,
625 NoneCoalescingOperator,
626}
627
628#[derive(Debug, Clone)]
630pub enum UnaryOperator {
631 Not(Node),
632 Negate(Node),
633 BorrowMutRef(Node),
634}
635
636#[derive(Debug, Clone)]
637pub struct GuardExpr {
638 pub clause: GuardClause,
639 pub result: Expression,
640}
641
642#[derive(Debug, Clone)]
643pub enum GuardClause {
644 Wildcard(Node),
645 Expression(Expression),
646}
647
648#[derive(Debug, Clone)]
650pub enum Pattern {
651 Wildcard(Node),
652 ConcretePattern(Node, ConcretePattern, Option<GuardClause>),
653}
654
655#[derive(Debug, Clone)]
656pub enum ConcretePattern {
657 EnumPattern(Node, DestructuringPattern), Literal(LiteralKind), }
660
661#[derive(Debug, Clone)]
662pub enum PatternVariableOrWildcard {
663 Variable(Variable),
664 Wildcard(Node),
665}
666
667#[derive(Debug, Clone)]
669pub enum DestructuringPattern {
670 Struct { fields: Vec<Variable> },
672
673 Tuple {
675 elements: Vec<PatternVariableOrWildcard>,
676 },
677
678 None { variable: Variable },
680
681 Unit,
683}
684
685#[derive(Debug, Clone)]
686pub enum StringPart {
687 Literal(Node, String),
688 Interpolation(Box<Expression>, Option<FormatSpecifier>),
689}
690
691#[derive(Debug, Clone)]
694pub enum FormatSpecifier {
695 LowerHex(Node), UpperHex(Node), Binary(Node), Float(Node), Precision(u32, Node, PrecisionType), }
701
702#[derive(Debug, Clone)]
703pub enum PrecisionType {
704 Float(Node),
705 String(Node),
706}
707
708#[derive(Debug, Clone)]
709pub enum AttributeArg {
710 Path(QualifiedIdentifier),
712 Literal(AttributeValue),
714 Function(QualifiedIdentifier, Vec<AttributeArg>),
716}
717
718#[derive(Debug, Clone)]
719pub enum AttributeLiteralKind {
720 Int,
721 String(String),
722 Bool,
723}
724
725#[derive(Debug, Clone)]
726pub enum AttributeValue {
727 Literal(Node, AttributeLiteralKind),
728 Path(QualifiedIdentifier),
729 Function(QualifiedIdentifier, Vec<AttributeArg>),
730}
731
732#[derive(Debug, Clone)]
733pub struct Attribute {
734 pub is_inner: bool,
735 pub path: QualifiedIdentifier,
736 pub args: Vec<AttributeArg>,
737 pub node: Node,
738}
739
740#[derive()]
741pub struct Module {
742 pub expression: Option<Expression>,
743 pub definitions: Vec<Definition>,
744}
745
746impl Debug for Module {
747 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
748 for definition in &self.definitions {
749 writeln!(f, "{definition:?}")?;
750 }
751
752 if !self.definitions.is_empty() && self.expression.is_some() {
753 writeln!(f, "---")?;
754 }
755
756 if let Some(found_expression) = &self.expression {
757 match &found_expression.kind {
758 ExpressionKind::Block(expressions) => {
759 for expression in expressions {
760 writeln!(f, "{expression:?}")?;
761 }
762 }
763 _ => writeln!(f, "{found_expression:?}")?,
764 }
765 }
766
767 Ok(())
768 }
769}
770
771impl Module {
772 #[must_use]
773 pub const fn new(definitions: Vec<Definition>, expression: Option<Expression>) -> Self {
774 Self {
775 expression,
776 definitions,
777 }
778 }
779
780 #[must_use]
781 pub const fn expression(&self) -> &Option<Expression> {
782 &self.expression
783 }
784
785 #[must_use]
786 pub const fn definitions(&self) -> &Vec<Definition> {
787 &self.definitions
788 }
789
790 #[must_use]
791 pub fn imports(&self) -> Vec<&Use> {
792 let mut use_items = Vec::new();
793
794 for def in &self.definitions {
795 if let DefinitionKind::Use(use_info) = &def.kind {
796 use_items.push(use_info);
797 }
798 }
799
800 use_items
801 }
802}