Skip to main content

constructo_runtime/
ast.rs

1//! The syntax trees for data-type declarations and data values.
2
3use crate::diagnostics::Pos;
4use std::fmt;
5
6/// The declarations of a types file.
7#[derive(Debug, Clone, PartialEq, Eq, Default)]
8pub struct TypesFile {
9    /// The enums, in the order of the file.
10    pub enums: Vec<EnumDecl>,
11    /// The consts, in the order of the file.
12    pub consts: Vec<ConstDecl>,
13}
14
15/// `const name<Params>: Type = value;`, in which the parameters and the type may be left out together.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ConstDecl {
18    /// The name of the const.
19    pub name: String,
20    /// The position of the name.
21    pub pos: Pos,
22    /// The type parameters, which are empty if there are none.
23    pub params: Vec<TypeParam>,
24    /// The declared type, or `None` if it is to be inferred from the value.
25    pub ty: Option<Type>,
26    /// The value of the const.
27    pub value: Value,
28}
29
30/// `enum Name<Params> = Variants;`
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct EnumDecl {
33    /// The name of the enum.
34    pub name: String,
35    /// The position of the name.
36    pub pos: Pos,
37    /// The type parameters, which are empty if there are none.
38    pub params: Vec<TypeParam>,
39    /// The variants, in the order of the file.
40    pub variants: Vec<Variant>,
41}
42
43/// A type parameter of an enum or a const, such as the `T` of `enum List<T>`.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct TypeParam {
46    /// The name of the parameter.
47    pub name: String,
48    /// The position of the name.
49    pub pos: Pos,
50    /// True for a parameter written with a leading underscore, which is allowed to be unused.
51    pub underscore: bool,
52}
53
54/// A variant of an enum, which is a constructor and what it takes.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Variant {
57    /// The name of the constructor.
58    pub name: String,
59    /// The position of the name.
60    pub pos: Pos,
61    /// What the constructor takes.
62    pub body: VariantBody,
63}
64
65/// What the constructor of a variant takes.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum VariantBody {
68    /// A bare constructor such as `Quit`.
69    Unit,
70    /// A record such as `Move { x: Int, y: Int }`.
71    Record(Vec<Field>),
72    /// A tuple such as `Write(String)` or `Image(String, hOffset: Nat)`, possibly empty as in `Ping()`.
73    Tuple(Vec<Parameter>),
74    /// An array of one element type, as in `Users[User]`. It is a different form from `Users([User])`.
75    Array(Type),
76}
77
78/// A parameter of a tuple constructor. Unnamed parameters come first and can only be bound by position.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct Parameter {
81    /// The name of the parameter, or `None` if it is unnamed.
82    pub name: Option<String>,
83    /// The position of the parameter.
84    pub pos: Pos,
85    /// The type of the parameter.
86    pub ty: Type,
87}
88
89/// A field of a record type.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Field {
92    /// The name of the field.
93    pub name: String,
94    /// The position of the name.
95    pub pos: Pos,
96    /// The type of the field.
97    pub ty: Type,
98}
99
100/// A type, as it is written in a declaration.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub enum Type {
103    /// A named type with its arguments, such as `Nat` or `List<Int>`.
104    Ref {
105        /// The name of the type, as it is written.
106        name: String,
107        /// The position of the name.
108        pos: Pos,
109        /// The type arguments, which are empty if there are none.
110        args: Vec<Type>,
111    },
112    /// An array of one element type, such as `[Nat]`.
113    Array(Box<Type>),
114    /// A record type without a name, such as `{ x: Int }`.
115    Record(Vec<Field>),
116}
117
118/// A data value.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct Value {
121    /// The position of the start of the value.
122    pub pos: Pos,
123    /// What the value is.
124    pub kind: ValueKind,
125}
126
127/// The kinds of a data value.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum ValueKind {
130    /// The literals keep their text, so that checking them against a type can decide how to interpret them.
131    /// An unsigned integer literal, such as `42`.
132    Nat(String),
133    /// A signed integer literal, such as `+8` or `-1`.
134    Int(String),
135    /// A floating-point literal, such as `3.0` or `-2.5e3`.
136    Float(String),
137    /// A string literal, with its escapes decoded.
138    Str(String),
139    /// An array, such as `[1, 2]`.
140    Array(Vec<Value>),
141    /// A record without a constructor, such as `{ x: 1 }`.
142    Record(Vec<Member>),
143    /// A constructor, optionally followed by a record, a tuple or an array, as in `Quit`, `Move { x: 1 }`,
144    /// `Write("hi")` or `Users[u1, u2]`.
145    /// A name that starts with a lower-case letter or `_` is a reference to a const, which takes no body, and any other
146    /// name is a constructor.
147    Tagged {
148        /// The name, as it is written, which may be qualified.
149        name: String,
150        /// What follows the name, or `None` if nothing does.
151        body: Option<TaggedBody>,
152    },
153}
154
155/// What follows the name of a constructor in a value.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub enum TaggedBody {
158    /// A record, such as the `{ x: 1 }` of `Move { x: 1 }`.
159    Record(Vec<Member>),
160    /// A tuple, possibly empty as in `Ping()`. Positional arguments come before any named ones.
161    Tuple(Vec<Argument>),
162    /// An array, possibly empty as in `Users[]`. It has no names, so every element is an ordinary value.
163    Array(Vec<Value>),
164}
165
166/// An argument of a tuple constructor, which is either positional or given by the name of a parameter.
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct Argument {
169    /// The name of the parameter, or `None` if the argument is positional.
170    pub name: Option<String>,
171    /// The position of the argument.
172    pub pos: Pos,
173    /// The value of the argument.
174    pub value: Value,
175}
176
177/// A member of a record value, `name: value`.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Member {
180    /// The name of the member.
181    pub name: String,
182    /// The position of the name.
183    pub pos: Pos,
184    /// The value of the member.
185    pub value: Value,
186}
187
188impl fmt::Display for Type {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        match self {
191            Type::Ref { name, args, .. } => {
192                write!(f, "{}", name)?;
193                if !args.is_empty() {
194                    let args: Vec<String> = args.iter().map(|t| t.to_string()).collect();
195                    write!(f, "<{}>", args.join(", "))?;
196                }
197                Ok(())
198            }
199            Type::Array(element) => write!(f, "[{}]", element),
200            Type::Record(fields) if fields.is_empty() => write!(f, "{{}}"),
201            Type::Record(fields) => {
202                let fields: Vec<String> = fields
203                    .iter()
204                    .map(|field| format!("{}: {}", field.name, field.ty))
205                    .collect();
206                write!(f, "{{ {} }}", fields.join(", "))
207            }
208        }
209    }
210}
211
212impl Value {
213    /// Collects the names that the value uses on their own or as the tag of a body, with their positions. Any of them
214    /// may refer to a const, which is for the caller to decide.
215    pub fn names<'a>(&'a self, out: &mut Vec<(&'a str, Pos)>) {
216        match &self.kind {
217            ValueKind::Array(items) => items.iter().for_each(|item| item.names(out)),
218            ValueKind::Record(members) => members.iter().for_each(|m| m.value.names(out)),
219            ValueKind::Tagged { name, body } => {
220                out.push((name, self.pos));
221                match body {
222                    Some(TaggedBody::Record(members)) => members.iter().for_each(|m| m.value.names(out)),
223                    Some(TaggedBody::Tuple(items)) => items.iter().for_each(|item| item.value.names(out)),
224                    Some(TaggedBody::Array(items)) => items.iter().for_each(|item| item.names(out)),
225                    None => {}
226                }
227            }
228            ValueKind::Nat(_) | ValueKind::Int(_) | ValueKind::Float(_) | ValueKind::Str(_) => {}
229        }
230    }
231}