Skip to main content

wright/ast/decl/
function.rs

1//! Function declarations, such as `func add(a: u8, b: u8) -> u8 { a + b }`.
2
3use crate::ast::{AstNode, identifier::Identifier, stmt::Block, ty::Type};
4use crate::source_tracking::fragment::Fragment;
5
6/// A function declaration.
7#[derive(Debug, Clone, PartialEq)]
8pub struct FunctionDecl {
9    /// Full matching source of the declaration.
10    pub matching_source: Fragment,
11
12    /// Modifiers such as `pure` or `unsafe`, in source order. The parser rejects duplicates.
13    pub modifiers: Vec<FunctionModifier>,
14
15    /// The name of the function.
16    pub name: Identifier,
17
18    /// Generic type parameters, such as the `T` in `func id<T>(t: T) -> T`.
19    pub generics: Vec<Identifier>,
20
21    /// The function's parameters, in order.
22    pub params: Vec<Param>,
23
24    /// The declared return type, if any.
25    pub return_ty: Option<Type>,
26
27    /// The body of the function. Functions declared without a body (`func f();`) have [None].
28    pub body: Option<Block>,
29}
30
31impl FunctionDecl {
32    /// Does this function have the given modifier?
33    pub fn has_modifier(&self, kind: FunctionModifierKind) -> bool {
34        self.modifiers.iter().any(|modifier| modifier.kind == kind)
35    }
36}
37
38/// A modifier on a [FunctionDecl].
39#[derive(Debug, Clone, PartialEq)]
40pub struct FunctionModifier {
41    /// The source of the modifier keyword.
42    pub matching_source: Fragment,
43
44    /// Which modifier it is.
45    pub kind: FunctionModifierKind,
46}
47
48impl AstNode for FunctionModifier {
49    fn matching_source(&self) -> &Fragment {
50        &self.matching_source
51    }
52}
53
54/// The kinds of [FunctionModifier]s.
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56pub enum FunctionModifierKind {
57    /// `pure` -- the function has no side effects.
58    Pure,
59    /// `unsafe` -- the function has invariants the compiler cannot check.
60    Unsafe,
61    /// `naked` -- the function has no prologue or epilogue generated for it.
62    Naked,
63}
64
65impl FunctionModifierKind {
66    /// Get the keyword for this modifier.
67    pub const fn keyword(self) -> &'static str {
68        match self {
69            FunctionModifierKind::Pure => "pure",
70            FunctionModifierKind::Unsafe => "unsafe",
71            FunctionModifierKind::Naked => "naked",
72        }
73    }
74}
75
76/// A parameter of a [FunctionDecl], such as `a: u8`.
77#[derive(Debug, Clone, PartialEq)]
78pub struct Param {
79    /// Full matching source of the parameter.
80    pub matching_source: Fragment,
81
82    /// The name of the parameter.
83    pub name: Identifier,
84
85    /// The type of the parameter.
86    pub ty: Type,
87}
88
89impl AstNode for Param {
90    fn matching_source(&self) -> &Fragment {
91        &self.matching_source
92    }
93}