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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
use core::fmt;

use super::{
    Export, Import, LocalNameResolver, ProcedureIndex, ProcedureName, QualifiedProcedureName,
    ResolvedProcedure,
};
use crate::{
    ast::{AliasTarget, Ident},
    diagnostics::{Report, SourceFile},
    parser::ModuleParser,
    sema::SemanticAnalysisError,
    ByteReader, ByteWriter, Deserializable, DeserializationError, LibraryNamespace, LibraryPath,
    Serializable, SourceSpan, Span, Spanned,
};

// MODULE KIND
// ================================================================================================

/// Represents the kind of a [Module].
///
/// The three different kinds have slightly different rules on what syntax is allowed, as well as
/// what operations can be performed in the body of procedures defined in the module. See the
/// documentation for each variant for a summary of these differences.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
#[repr(u8)]
pub enum ModuleKind {
    /// A library is a simple container of code that must be included into an executable module to
    /// form a complete program.
    ///
    /// Library modules cannot use the `begin`..`end` syntax, which is used to define the
    /// entrypoint procedure for an executable. Aside from this, they are free to use all other
    /// MASM syntax.
    #[default]
    Library = 0,
    /// An executable is the root module of a program, and provides the entrypoint for executing
    /// that program.
    ///
    /// As the executable module is the root module, it may not export procedures for other modules
    /// to depend on, it may only import and call externally-defined procedures, or private
    /// locally-defined procedures.
    ///
    /// An executable module must contain a `begin`..`end` block.
    Executable = 1,
    /// A kernel is like a library module, but is special in a few ways:
    ///
    /// * Its code always executes in the root context, so it is stateful in a way that normal
    ///   libraries cannot replicate. This can be used to provide core services that would
    ///   otherwise not be possible to implement.
    ///
    /// * The procedures exported from the kernel may be the target of the `syscall` instruction,
    ///   and in fact _must_ be called that way.
    ///
    /// * Kernels may not use `syscall` or `call` instructions internally.
    Kernel = 2,
}

impl ModuleKind {
    pub fn is_executable(&self) -> bool {
        matches!(self, Self::Executable)
    }

    pub fn is_kernel(&self) -> bool {
        matches!(self, Self::Kernel)
    }

    pub fn is_library(&self) -> bool {
        matches!(self, Self::Library)
    }
}

impl fmt::Display for ModuleKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Library => f.write_str("library"),
            Self::Executable => f.write_str("executable"),
            Self::Kernel => f.write_str("kernel"),
        }
    }
}

impl Serializable for ModuleKind {
    fn write_into<W: ByteWriter>(&self, target: &mut W) {
        target.write_u8(*self as u8)
    }
}

impl Deserializable for ModuleKind {
    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        match source.read_u8()? {
            0 => Ok(Self::Library),
            1 => Ok(Self::Executable),
            2 => Ok(Self::Kernel),
            n => Err(DeserializationError::InvalidValue(format!("invalid module kind tag: {n}"))),
        }
    }
}

// MODULE
// ================================================================================================

/// The abstract syntax tree for a single Miden Assembly module.
///
/// All module kinds share this AST representation, as they are largely identical. However, the
/// [ModuleKind] dictates how the parsed module is semantically analyzed and validated.
#[derive(Clone)]
pub struct Module {
    /// The span covering the entire definition of this module.
    span: SourceSpan,
    /// The documentation associated with this module.
    ///
    /// Module documentation is provided in Miden Assembly as a documentation comment starting on
    /// the first line of the module. All other documentation comments are attached to the item the
    /// precede in the module body.
    docs: Option<Span<String>>,
    /// The fully-qualified path representing the name of this module.
    path: LibraryPath,
    /// The kind of module this represents.
    kind: ModuleKind,
    /// The imports defined in the module body.
    pub(crate) imports: Vec<Import>,
    /// The procedures (defined or re-exported) in the module body.
    ///
    /// NOTE: Despite the name, the procedures in this set are not necessarily exported, the
    /// individual procedure item must be checked to determine visibility.
    pub(crate) procedures: Vec<Export>,
}

/// Constants
impl Module {
    /// File extension for a Assembly Module.
    pub const FILE_EXTENSION: &'static str = "masm";

    /// Name of the root module.
    pub const ROOT: &'static str = "mod";

    /// File name of the root module.
    pub const ROOT_FILENAME: &'static str = "mod.masm";
}

/// Construction
impl Module {
    /// Creates a new [Module] with the specified `kind` and fully-qualified path, e.g.
    /// `std::math::u64`.
    pub fn new(kind: ModuleKind, path: LibraryPath) -> Self {
        Self {
            span: Default::default(),
            docs: None,
            path,
            kind,
            imports: Default::default(),
            procedures: Default::default(),
        }
    }

    /// An alias for creating the default, but empty, `#kernel` [Module].
    pub fn new_kernel() -> Self {
        Self::new(ModuleKind::Kernel, LibraryNamespace::Kernel.into())
    }

    /// An alias for creating the default, but empty, `#exec` [Module].
    pub fn new_executable() -> Self {
        Self::new(ModuleKind::Executable, LibraryNamespace::Exec.into())
    }

    /// Specifies the source span in the source file in which this module was defined, that covers
    /// the full definition of this module.
    pub fn with_span(mut self, span: SourceSpan) -> Self {
        self.span = span;
        self
    }

    /// Sets the [LibraryPath] for this module
    pub fn set_path(&mut self, path: LibraryPath) {
        self.path = path;
    }

    /// Sets the [LibraryNamespace] for this module
    pub fn set_namespace(&mut self, ns: LibraryNamespace) {
        self.path.set_namespace(ns);
    }

    /// Sets the documentation for this module
    pub fn set_docs(&mut self, docs: Option<Span<String>>) {
        self.docs = docs;
    }

    /// Like [Module::with_span], but does not require ownership of the [Module].
    pub fn set_span(&mut self, span: SourceSpan) {
        self.span = span;
    }

    /// Defines a procedure, raising an error if the procedure is invalid, or conflicts with a
    /// previous definition
    pub fn define_procedure(&mut self, export: Export) -> Result<(), SemanticAnalysisError> {
        if self.is_kernel() && matches!(export, Export::Alias(_)) {
            return Err(SemanticAnalysisError::ReexportFromKernel { span: export.span() });
        }
        if let Some(prev) = self.resolve(export.name()) {
            let prev_span = prev.span();
            Err(SemanticAnalysisError::SymbolConflict { span: export.span(), prev_span })
        } else {
            self.procedures.push(export);
            Ok(())
        }
    }

    /// Defines an import, raising an error if the import is invalid, or conflicts with a previous
    /// definition.
    pub fn define_import(&mut self, import: Import) -> Result<(), SemanticAnalysisError> {
        if let Some(prev_import) = self.resolve_import(&import.name) {
            let prev_span = prev_import.span;
            return Err(SemanticAnalysisError::ImportConflict { span: import.span, prev_span });
        }

        if let Some(prev_defined) = self.procedures.iter().find(|e| e.name().eq(&import.name)) {
            let prev_span = prev_defined.span();
            return Err(SemanticAnalysisError::SymbolConflict { span: import.span, prev_span });
        }

        self.imports.push(import);

        Ok(())
    }
}

/// Parsing
impl Module {
    /// Parse a [Module], `name`, of the given [ModuleKind], from `source_file`.
    pub fn parse(
        name: LibraryPath,
        kind: ModuleKind,
        source_file: Arc<SourceFile>,
    ) -> Result<Box<Self>, Report> {
        let mut parser = Self::parser(kind);
        parser.parse(name, source_file)
    }

    /// Get a [ModuleParser] for parsing modules of the provided [ModuleKind]
    pub fn parser(kind: ModuleKind) -> ModuleParser {
        ModuleParser::new(kind)
    }
}

/// Metadata
impl Module {
    /// Get the name of this specific module, i.e. the last component of the [LibraryPath] that
    /// represents the fully-qualified name of the module, e.g. `u64` in `std::math::u64`
    pub fn name(&self) -> &str {
        self.path.last()
    }

    /// Get the fully-qualified name of this module, e.g. `std::math::u64`
    pub fn path(&self) -> &LibraryPath {
        &self.path
    }

    /// Get the namespace of this module, e.g. `std` in `std::math::u64`
    pub fn namespace(&self) -> &LibraryNamespace {
        self.path.namespace()
    }

    /// Returns true if this module belongs to the provided namespace.
    pub fn is_in_namespace(&self, namespace: &LibraryNamespace) -> bool {
        self.path.namespace() == namespace
    }

    /// Get the module documentation for this module, if it was present in the source code the
    /// module was parsed from
    pub fn docs(&self) -> Option<Span<&str>> {
        self.docs.as_ref().map(|spanned| spanned.as_deref())
    }

    /// Get the type of module this represents:
    ///
    /// See [ModuleKind] for details on the different types of modules.
    pub fn kind(&self) -> ModuleKind {
        self.kind
    }

    /// Returns true if this module is an executable module.
    #[inline(always)]
    pub fn is_executable(&self) -> bool {
        self.kind.is_executable()
    }

    /// Returns true if this module is a kernel module.
    #[inline(always)]
    pub fn is_kernel(&self) -> bool {
        self.kind.is_kernel()
    }

    /// Returns true if this module has an entrypoint procedure defined,
    /// i.e. a `begin`..`end` block.
    pub fn has_entrypoint(&self) -> bool {
        self.index_of(|p| p.is_main()).is_some()
    }

    /// Get an iterator over the procedures defined in this module.
    ///
    /// The entity returned is an [Export], which abstracts over locally-defined procedures and
    /// re-exported procedures from imported modules.
    pub fn procedures(&self) -> core::slice::Iter<'_, Export> {
        self.procedures.iter()
    }

    /// Same as [Module::procedures], but returns mutable references.
    pub fn procedures_mut(&mut self) -> core::slice::IterMut<'_, Export> {
        self.procedures.iter_mut()
    }

    /// Returns procedures exported from this module.
    ///
    /// Each exported procedure is represented by its local procedure index and a fully qualified
    /// name.
    pub fn exported_procedures(
        &self,
    ) -> impl Iterator<Item = (ProcedureIndex, QualifiedProcedureName)> + '_ {
        self.procedures.iter().enumerate().filter_map(|(proc_idx, p)| {
            // skip un-exported procedures
            if !p.visibility().is_exported() {
                return None;
            }

            let proc_idx = ProcedureIndex::new(proc_idx);
            let fqn = QualifiedProcedureName::new(self.path().clone(), p.name().clone());

            Some((proc_idx, fqn))
        })
    }

    /// Get an iterator over the imports declared in this module.
    ///
    /// See [Import] for details on what information is available for imports.
    pub fn imports(&self) -> core::slice::Iter<'_, Import> {
        self.imports.iter()
    }

    /// Same as [Self::imports], but returns mutable references to each import.
    pub fn imports_mut(&mut self) -> core::slice::IterMut<'_, Import> {
        self.imports.iter_mut()
    }

    /// Get an iterator over the "dependencies" of a module, i.e. what library namespaces we expect
    /// to find imported procedures in.
    ///
    /// For example, if we have imported `std::math::u64`, then we would expect to find a library
    /// on disk named `std.masl`, although that isn't a strict requirement. This notion of
    /// dependencies may go away with future packaging-related changed.
    pub fn dependencies(&self) -> impl Iterator<Item = &LibraryNamespace> {
        self.import_paths().map(|import| import.namespace())
    }

    /// Get the procedure at `index` in this module's procedure table.
    ///
    /// The procedure returned may be either a locally-defined procedure, or a re-exported
    /// procedure. See [Export] for details.
    pub fn get(&self, index: ProcedureIndex) -> Option<&Export> {
        self.procedures.get(index.as_usize())
    }

    /// Get the [ProcedureIndex] for the first procedure in this module's procedure table which
    /// returns true for `predicate`.
    pub fn index_of<F>(&self, predicate: F) -> Option<ProcedureIndex>
    where
        F: FnMut(&Export) -> bool,
    {
        self.procedures.iter().position(predicate).map(ProcedureIndex::new)
    }

    /// Get the [ProcedureIndex] for the procedure whose name is `name` in this module's procedure
    /// table, _if_ that procedure is exported.
    ///
    /// Non-exported procedures can be retrieved by using [Module::index_of].
    pub fn index_of_name(&self, name: &ProcedureName) -> Option<ProcedureIndex> {
        self.index_of(|p| p.name() == name && p.visibility().is_exported())
    }

    /// Resolves `name` to a procedure within the local scope of this module
    pub fn resolve(&self, name: &ProcedureName) -> Option<ResolvedProcedure> {
        let index =
            self.procedures.iter().position(|p| p.name() == name).map(ProcedureIndex::new)?;
        match &self.procedures[index.as_usize()] {
            Export::Procedure(ref proc) => {
                Some(ResolvedProcedure::Local(Span::new(proc.name().span(), index)))
            },
            Export::Alias(ref alias) => match alias.target() {
                AliasTarget::MastRoot(digest) => Some(ResolvedProcedure::MastRoot(**digest)),
                AliasTarget::ProcedurePath(path) | AliasTarget::AbsoluteProcedurePath(path) => {
                    Some(ResolvedProcedure::External(path.clone()))
                },
            },
        }
    }

    /// Construct a search structure that can resolve procedure names local to this module
    pub fn resolver(&self) -> LocalNameResolver {
        LocalNameResolver::from_iter(self.procedures.iter().enumerate().map(|(i, p)| match p {
            Export::Procedure(ref p) => (
                p.name().clone(),
                ResolvedProcedure::Local(Span::new(p.name().span(), ProcedureIndex::new(i))),
            ),
            Export::Alias(ref p) => {
                let target = match p.target() {
                    AliasTarget::MastRoot(digest) => ResolvedProcedure::MastRoot(**digest),
                    AliasTarget::ProcedurePath(path) | AliasTarget::AbsoluteProcedurePath(path) => {
                        ResolvedProcedure::External(path.clone())
                    },
                };
                (p.name().clone(), target)
            },
        }))
        .with_imports(
            self.imports
                .iter()
                .map(|import| (import.name.clone(), Span::new(import.span(), import.path.clone()))),
        )
    }

    /// Resolves `module_name` to an [Import] within the context of this module
    pub fn resolve_import(&self, module_name: &Ident) -> Option<&Import> {
        self.imports.iter().find(|import| &import.name == module_name)
    }

    /// Same as [Module::resolve_import], but returns a mutable reference to the [Import]
    pub fn resolve_import_mut(&mut self, module_name: &Ident) -> Option<&mut Import> {
        self.imports.iter_mut().find(|import| &import.name == module_name)
    }

    /// Return an iterator over the paths of all imports in this module
    pub fn import_paths(&self) -> impl Iterator<Item = &LibraryPath> + '_ {
        self.imports.iter().map(|import| &import.path)
    }
}

impl core::ops::Index<ProcedureIndex> for Module {
    type Output = Export;

    #[inline]
    fn index(&self, index: ProcedureIndex) -> &Self::Output {
        &self.procedures[index.as_usize()]
    }
}

impl core::ops::IndexMut<ProcedureIndex> for Module {
    #[inline]
    fn index_mut(&mut self, index: ProcedureIndex) -> &mut Self::Output {
        &mut self.procedures[index.as_usize()]
    }
}

impl Spanned for Module {
    fn span(&self) -> SourceSpan {
        self.span
    }
}

impl Eq for Module {}

impl PartialEq for Module {
    fn eq(&self, other: &Self) -> bool {
        self.kind == other.kind
            && self.path == other.path
            && self.docs == other.docs
            && self.imports == other.imports
            && self.procedures == other.procedures
    }
}

/// Debug representation of this module
impl fmt::Debug for Module {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Module")
            .field("docs", &self.docs)
            .field("path", &self.path)
            .field("kind", &self.kind)
            .field("imports", &self.imports)
            .field("procedures", &self.procedures)
            .finish()
    }
}

/// Pretty-printed representation of this module as Miden Assembly text format
///
/// NOTE: Delegates to the [crate::prettier::PrettyPrint] implementation internally
impl fmt::Display for Module {
    /// Writes this [Module] as formatted MASM code into the formatter.
    ///
    /// The formatted code puts each instruction on a separate line and preserves correct
    /// indentation for instruction blocks.
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use crate::prettier::PrettyPrint;

        self.pretty_print(f)
    }
}

/// The pretty-printer for [Module]
impl crate::prettier::PrettyPrint for Module {
    fn render(&self) -> crate::prettier::Document {
        use crate::prettier::*;

        let mut doc = Document::Empty;
        if let Some(docs) = self.docs.as_ref() {
            let fragment =
                docs.lines().map(text).reduce(|acc, line| acc + nl() + text("#! ") + line);

            if let Some(fragment) = fragment {
                doc += fragment;
            }
        }

        for (i, import) in self.imports.iter().enumerate() {
            if i > 0 {
                doc += nl();
            }
            doc += import.render();
        }

        if !self.imports.is_empty() {
            doc += nl();
        }

        let mut export_index = 0;
        for export in self.procedures.iter() {
            if export.is_main() {
                continue;
            }
            if export_index > 0 {
                doc += nl();
            }
            doc += export.render();
            export_index += 1;
        }

        if let Some(main) = self.procedures().find(|p| p.is_main()) {
            doc += main.render();
        }

        doc
    }
}