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
mod block;
mod convert;
mod functions;
mod globals;
mod instruction;

use alloc::collections::BTreeMap;
use core::fmt;

pub use self::{block::*, convert::ConvertAstToHir, functions::*, globals::*, instruction::*};
use crate::{
    diagnostics::{DiagnosticsHandler, Severity, SourceSpan, Span, Spanned},
    ExternalFunction, FunctionIdent, Ident,
};

/// This represents the parsed contents of a single Miden IR module
#[derive(Spanned)]
pub struct Module {
    #[span]
    pub span: SourceSpan,
    pub name: Ident,
    pub constants: Vec<ConstantDeclaration>,
    pub global_vars: Vec<GlobalVarDeclaration>,
    pub data_segments: Vec<DataSegmentDeclaration>,
    pub functions: Vec<FunctionDeclaration>,
    pub externals: Vec<Span<ExternalFunction>>,
    pub is_kernel: bool,
}
impl fmt::Debug for Module {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Module")
            .field("name", &self.name.as_symbol())
            .field("constants", &self.constants)
            .field("global_vars", &self.global_vars)
            .field("data_segments", &self.data_segments)
            .field("functions", &self.functions)
            .field("externals", &self.externals)
            .field("is_kernel", &self.is_kernel)
            .finish()
    }
}
impl midenc_session::Emit for Module {
    fn name(&self) -> Option<crate::Symbol> {
        Some(self.name.as_symbol())
    }

    fn output_type(&self, _mode: midenc_session::OutputMode) -> midenc_session::OutputType {
        midenc_session::OutputType::Ast
    }

    fn write_to<W: std::io::Write>(
        &self,
        mut writer: W,
        mode: midenc_session::OutputMode,
        _session: &midenc_session::Session,
    ) -> std::io::Result<()> {
        assert_eq!(
            mode,
            midenc_session::OutputMode::Text,
            "binary mode is not supported for HIR syntax trees"
        );
        writer.write_fmt(format_args!("{:#?}", self))
    }
}

type ConstantsById = BTreeMap<crate::Constant, Span<crate::ConstantData>>;
type RemappedConstants = BTreeMap<crate::Constant, crate::Constant>;
type GlobalVariablesById = BTreeMap<crate::GlobalVariable, Span<crate::GlobalVariableData>>;
type ImportsById = BTreeMap<FunctionIdent, Span<crate::ExternalFunction>>;
type BlocksById = BTreeMap<crate::Block, Block>;
type ValuesById = BTreeMap<crate::Value, Span<crate::ValueData>>;
type InstResults = BTreeMap<crate::Inst, Vec<crate::Value>>;

impl Module {
    pub fn new(span: SourceSpan, name: Ident, is_kernel: bool, forms: Vec<Form>) -> Self {
        let mut module = Self {
            span,
            name,
            constants: vec![],
            functions: vec![],
            externals: vec![],
            global_vars: vec![],
            data_segments: vec![],
            is_kernel,
        };
        for form in forms.into_iter() {
            match form {
                Form::Constant(constant) => {
                    module.constants.push(constant);
                }
                Form::Global(global) => {
                    module.global_vars.push(global);
                }
                Form::DataSegment(segment) => {
                    module.data_segments.push(segment);
                }
                Form::Function(function) => {
                    module.functions.push(function);
                }
                Form::ExternalFunction(external) => {
                    module.externals.push(external);
                }
            }
        }
        module
    }

    fn take_and_validate_constants(
        &mut self,
        diagnostics: &DiagnosticsHandler,
    ) -> (ConstantsById, bool) {
        use alloc::collections::btree_map::Entry;

        let mut constants_by_id = ConstantsById::default();
        let constants = core::mem::take(&mut self.constants);
        let mut is_valid = true;
        for constant in constants.into_iter() {
            match constants_by_id.entry(constant.id) {
                Entry::Vacant(entry) => {
                    entry.insert(Span::new(constant.span, constant.init));
                }
                Entry::Occupied(entry) => {
                    let prev = entry.get().span();
                    diagnostics
                        .diagnostic(Severity::Error)
                        .with_message("invalid constant declaration")
                        .with_primary_label(
                            constant.span,
                            "a constant with this identifier has already been declared",
                        )
                        .with_secondary_label(prev, "previously declared here")
                        .emit();
                    is_valid = false;
                }
            }
        }

        (constants_by_id, is_valid)
    }

    fn take_and_validate_globals(
        &mut self,
        remapped_constants: &RemappedConstants,
        diagnostics: &DiagnosticsHandler,
    ) -> (GlobalVariablesById, bool) {
        use alloc::collections::btree_map::Entry;

        let mut globals_by_id = GlobalVariablesById::default();
        let global_vars = core::mem::take(&mut self.global_vars);
        let mut is_valid = true;
        for global in global_vars.into_iter() {
            match globals_by_id.entry(global.id) {
                Entry::Vacant(entry) => {
                    if let Some(id) = global.init {
                        if !remapped_constants.contains_key(&id) {
                            let id = id.as_u32();
                            diagnostics
                                .diagnostic(Severity::Error)
                                .with_message("invalid global variable declaration")
                                .with_primary_label(
                                    global.span,
                                    format!(
                                        "invalid initializer: no constant named '{id}' in this \
                                         module"
                                    ),
                                )
                                .emit();
                            is_valid = false;
                        }
                    }
                    let gv = crate::GlobalVariableData::new(
                        global.id,
                        global.name,
                        global.ty,
                        global.linkage,
                        global.init.map(|id| remapped_constants[&id]),
                    );
                    entry.insert(Span::new(global.span, gv));
                }
                Entry::Occupied(entry) => {
                    let prev = entry.get().span();
                    diagnostics
                        .diagnostic(Severity::Error)
                        .with_message("invalid global variable declaration")
                        .with_primary_label(
                            global.span,
                            "a global variable with the same id has already been declared",
                        )
                        .with_secondary_label(prev, "previously declared here")
                        .emit();
                    is_valid = false;
                }
            }
        }

        (globals_by_id, is_valid)
    }

    fn take_and_validate_imports(
        &mut self,
        diagnostics: &DiagnosticsHandler,
    ) -> (ImportsById, bool) {
        use alloc::collections::btree_map::Entry;

        let mut imports_by_id = ImportsById::default();
        let mut is_valid = true;
        for external in core::mem::take(&mut self.externals).into_iter() {
            if external.id.module == self.name {
                diagnostics
                    .diagnostic(Severity::Error)
                    .with_message("invalid external function declaration")
                    .with_primary_label(
                        external.span(),
                        "external function declarations may not reference functions in the \
                         current module",
                    )
                    .emit();
                is_valid = false;
                continue;
            }

            match imports_by_id.entry(external.id) {
                Entry::Vacant(entry) => {
                    entry.insert(external);
                }
                Entry::Occupied(entry) => {
                    let prev = entry.get().span();
                    diagnostics
                        .diagnostic(Severity::Error)
                        .with_message("invalid external function declaration")
                        .with_primary_label(
                            external.span(),
                            "an external function with the same name has already been declared",
                        )
                        .with_secondary_label(prev, "previously declared here")
                        .emit();
                    is_valid = false;
                }
            }
        }

        (imports_by_id, is_valid)
    }
}

impl PartialEq for Module {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.is_kernel == other.is_kernel
            && self.global_vars == other.global_vars
            && self.data_segments == other.data_segments
            && self.functions == other.functions
            && self.externals == other.externals
    }
}

/// This represents one of the top-level forms which a [Module] can contain
#[derive(Debug)]
pub enum Form {
    Constant(ConstantDeclaration),
    Global(GlobalVarDeclaration),
    DataSegment(DataSegmentDeclaration),
    Function(FunctionDeclaration),
    ExternalFunction(Span<ExternalFunction>),
}