mimium-lang 4.0.1

mimium(minimal-musical-medium) an infrastructural programming language for sound and music.
Documentation
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
/// Green Tree - Concrete Syntax Tree (CST) for full-fidelity representation
/// Based on the Red-Green Syntax Tree pattern
///
/// Green nodes are immutable and position-independent. They represent
/// the structure of the syntax tree without absolute positions.
/// Green trees use interning via SlotMap for efficient sharing and caching.
use slotmap::{SlotMap, new_key_type};

new_key_type! {
    /// A handle to an interned GreenNode
    pub struct GreenNodeId;
}

/// Green node - represents a CST node without position information
/// This is the "Green" part of Red-Green Syntax Tree
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GreenNode {
    /// A token node (leaf)
    Token {
        token_index: usize,
        width: usize, // Length in bytes
    },

    /// An internal node with children
    Internal {
        kind: SyntaxKind,
        children: Vec<GreenNodeId>,
        width: usize, // Total width of all children
    },
}

impl GreenNode {
    /// Get the width (length in bytes) of this node
    pub fn width(&self) -> usize {
        match self {
            GreenNode::Token { width, .. } => *width,
            GreenNode::Internal { width, .. } => *width,
        }
    }

    /// Get the kind of this node
    pub fn kind(&self) -> Option<SyntaxKind> {
        match self {
            GreenNode::Token { .. } => None,
            GreenNode::Internal { kind, .. } => Some(*kind),
        }
    }

    /// Get children if this is an internal node
    pub fn children(&self) -> Option<&[GreenNodeId]> {
        match self {
            GreenNode::Token { .. } => None,
            GreenNode::Internal { children, .. } => Some(children),
        }
    }
}

/// Arena for interning Green nodes
#[derive(Debug, Default, Clone)]
pub struct GreenNodeArena {
    nodes: SlotMap<GreenNodeId, GreenNode>,
}

impl GreenNodeArena {
    /// Create a new arena
    pub fn new() -> Self {
        Self {
            nodes: SlotMap::with_key(),
        }
    }

    /// Intern a token node
    pub fn alloc_token(&mut self, token_index: usize, width: usize) -> GreenNodeId {
        self.nodes.insert(GreenNode::Token { token_index, width })
    }

    /// Intern an internal node
    pub fn alloc_internal(&mut self, kind: SyntaxKind, children: Vec<GreenNodeId>) -> GreenNodeId {
        let width = children.iter().map(|&id| self.nodes[id].width()).sum();
        self.nodes.insert(GreenNode::Internal {
            kind,
            children,
            width,
        })
    }

    /// Get a node by its ID
    pub fn get(&self, id: GreenNodeId) -> &GreenNode {
        &self.nodes[id]
    }

    /// Get the width of a node
    pub fn width(&self, id: GreenNodeId) -> usize {
        self.nodes[id].width()
    }

    /// Get the kind of a node
    pub fn kind(&self, id: GreenNodeId) -> Option<SyntaxKind> {
        self.nodes[id].kind()
    }

    /// Get children of a node
    pub fn children(&self, id: GreenNodeId) -> Option<&[GreenNodeId]> {
        self.nodes[id].children()
    }

    /// Pretty-print the CST tree structure with indentation.
    ///
    /// # Arguments
    /// * `node_id` - The root node to print from
    /// * `tokens` - Token slice for extracting token text
    /// * `source` - Original source code
    /// * `indent` - Current indentation level
    ///
    /// # Returns
    /// A formatted string representation of the tree
    pub fn print_tree(
        &self,
        node_id: GreenNodeId,
        tokens: &[crate::compiler::parser::Token],
        source: &str,
        indent: usize,
    ) -> String {
        use std::fmt::Write;
        let mut result = String::new();
        let indent_str = "  ".repeat(indent);

        match self.get(node_id) {
            GreenNode::Token { token_index, .. } => {
                let token = &tokens[*token_index];
                let text = token.text(source);
                // Escape newlines and special characters for display
                let escaped_text = text
                    .replace('\\', "\\\\")
                    .replace('\n', "\\n")
                    .replace('\r', "\\r")
                    .replace('\t', "\\t");
                let _ = writeln!(result, "{indent_str}{:?} \"{}\"", token.kind, escaped_text);
            }
            GreenNode::Internal { kind, children, .. } => {
                let _ = writeln!(result, "{indent_str}{kind}");
                for &child in children {
                    result.push_str(&self.print_tree(child, tokens, source, indent + 1));
                }
            }
        }
        result
    }
}

/// Syntax kinds - types of CST nodes
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SyntaxKind {
    // Top-level
    Program,
    Statement,

    // Declarations
    FunctionDecl,
    LetDecl,
    LetRecDecl,

    // Expressions
    BinaryExpr,
    UnaryExpr,
    ParenExpr,
    CallExpr,
    FieldAccess,
    IndexExpr,
    AssignExpr,
    ArrayExpr,
    MacroExpansion,
    BracketExpr,
    EscapeExpr,
    LambdaExpr,
    IfExpr,
    MatchExpr,
    MatchArm,
    MatchArmList,
    MatchPattern,
    ConstructorPattern,
    BlockExpr,
    TupleExpr,
    RecordExpr,

    // Literals
    IntLiteral,
    FloatLiteral,
    StringLiteral,
    SelfLiteral,
    NowLiteral,
    SampleRateLiteral,
    PlaceHolderLiteral,

    // Names and paths
    Identifier,

    // Types
    TypeAnnotation,
    PrimitiveType,
    UnitType,
    FunctionType,
    TupleType,
    RecordType,
    ArrayType,
    CodeType,
    UnionType,
    TypeIdent,

    // Patterns
    Pattern,
    SinglePattern,
    TuplePattern,
    RecordPattern,

    // Top-level statements
    IncludeStmt,
    StageDecl,
    ModuleDecl,
    UseStmt,
    TypeDecl,
    VariantDef,

    // Module-related
    QualifiedPath,
    VisibilityPub,
    UseTargetMultiple, // use foo::{bar, baz}
    UseTargetWildcard, // use foo::*

    // Lists and sequences
    ParamList,
    ArgList,
    ExprList,
    ParamDefault,

    // Other
    Error, // For error recovery
}

impl std::fmt::Display for SyntaxKind {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            SyntaxKind::Program => write!(f, "Program"),
            SyntaxKind::Statement => write!(f, "Statement"),
            SyntaxKind::FunctionDecl => write!(f, "FunctionDecl"),
            SyntaxKind::LetDecl => write!(f, "LetDecl"),
            SyntaxKind::LetRecDecl => write!(f, "LetRecDecl"),
            SyntaxKind::BinaryExpr => write!(f, "BinaryExpr"),
            SyntaxKind::UnaryExpr => write!(f, "UnaryExpr"),
            SyntaxKind::ParenExpr => write!(f, "ParenExpr"),
            SyntaxKind::CallExpr => write!(f, "CallExpr"),
            SyntaxKind::FieldAccess => write!(f, "FieldAccess"),
            SyntaxKind::IndexExpr => write!(f, "IndexExpr"),
            SyntaxKind::AssignExpr => write!(f, "AssignExpr"),
            SyntaxKind::ArrayExpr => write!(f, "ArrayExpr"),
            SyntaxKind::MacroExpansion => write!(f, "MacroExpansion"),
            SyntaxKind::BracketExpr => write!(f, "BracketExpr"),
            SyntaxKind::EscapeExpr => write!(f, "EscapeExpr"),
            SyntaxKind::LambdaExpr => write!(f, "LambdaExpr"),
            SyntaxKind::IfExpr => write!(f, "IfExpr"),
            SyntaxKind::MatchExpr => write!(f, "MatchExpr"),
            SyntaxKind::MatchArm => write!(f, "MatchArm"),
            SyntaxKind::MatchArmList => write!(f, "MatchArmList"),
            SyntaxKind::MatchPattern => write!(f, "MatchPattern"),
            SyntaxKind::ConstructorPattern => write!(f, "ConstructorPattern"),
            SyntaxKind::BlockExpr => write!(f, "BlockExpr"),
            SyntaxKind::TupleExpr => write!(f, "TupleExpr"),
            SyntaxKind::RecordExpr => write!(f, "RecordExpr"),
            SyntaxKind::IntLiteral => write!(f, "IntLiteral"),
            SyntaxKind::FloatLiteral => write!(f, "FloatLiteral"),
            SyntaxKind::StringLiteral => write!(f, "StringLiteral"),
            SyntaxKind::SelfLiteral => write!(f, "SelfLiteral"),
            SyntaxKind::NowLiteral => write!(f, "NowLiteral"),
            SyntaxKind::SampleRateLiteral => write!(f, "SampleRateLiteral"),
            SyntaxKind::PlaceHolderLiteral => write!(f, "PlaceHolderLiteral"),
            SyntaxKind::Identifier => write!(f, "Identifier"),
            SyntaxKind::TypeAnnotation => write!(f, "TypeAnnotation"),
            SyntaxKind::PrimitiveType => write!(f, "PrimitiveType"),
            SyntaxKind::UnitType => write!(f, "UnitType"),
            SyntaxKind::FunctionType => write!(f, "FunctionType"),
            SyntaxKind::TupleType => write!(f, "TupleType"),
            SyntaxKind::RecordType => write!(f, "RecordType"),
            SyntaxKind::ArrayType => write!(f, "ArrayType"),
            SyntaxKind::CodeType => write!(f, "CodeType"),
            SyntaxKind::UnionType => write!(f, "UnionType"),
            SyntaxKind::TypeIdent => write!(f, "TypeIdent"),
            SyntaxKind::Pattern => write!(f, "Pattern"),
            SyntaxKind::SinglePattern => write!(f, "SinglePattern"),
            SyntaxKind::TuplePattern => write!(f, "TuplePattern"),
            SyntaxKind::RecordPattern => write!(f, "RecordPattern"),
            SyntaxKind::IncludeStmt => write!(f, "IncludeStmt"),
            SyntaxKind::StageDecl => write!(f, "StageDecl"),
            SyntaxKind::ModuleDecl => write!(f, "ModuleDecl"),
            SyntaxKind::UseStmt => write!(f, "UseStmt"),
            SyntaxKind::TypeDecl => write!(f, "TypeDecl"),
            SyntaxKind::VariantDef => write!(f, "VariantDef"),
            SyntaxKind::QualifiedPath => write!(f, "QualifiedPath"),
            SyntaxKind::VisibilityPub => write!(f, "VisibilityPub"),
            SyntaxKind::UseTargetMultiple => write!(f, "UseTargetMultiple"),
            SyntaxKind::UseTargetWildcard => write!(f, "UseTargetWildcard"),
            SyntaxKind::ParamList => write!(f, "ParamList"),
            SyntaxKind::ArgList => write!(f, "ArgList"),
            SyntaxKind::ExprList => write!(f, "ExprList"),
            SyntaxKind::ParamDefault => write!(f, "ParamDefault"),
            SyntaxKind::Error => write!(f, "Error"),
        }
    }
}

/// A marker representing a position in the parse tree building process.
/// Used to wrap previously parsed nodes into a new parent node.
#[derive(Clone, Copy, Debug)]
pub struct Marker {
    /// Position in the children list of the current node when the marker was created
    pub pos: usize,
}

/// A builder for constructing Green Trees with an arena
pub struct GreenTreeBuilder {
    arena: GreenNodeArena,
    stack: Vec<(SyntaxKind, Vec<GreenNodeId>)>,
}

impl GreenTreeBuilder {
    pub fn new() -> Self {
        Self {
            arena: GreenNodeArena::new(),
            stack: Vec::new(),
        }
    }

    /// Get a reference to the arena
    pub fn arena(&self) -> &GreenNodeArena {
        &self.arena
    }

    /// Take ownership of the arena
    pub fn into_arena(self) -> GreenNodeArena {
        self.arena
    }

    /// Create a marker at the current position.
    /// This marker can be used later to wrap nodes parsed after this point
    /// into a new parent node using `start_node_at`.
    pub fn marker(&self) -> Marker {
        let pos = self
            .stack
            .last()
            .map(|(_, children)| children.len())
            .unwrap_or(0);
        Marker { pos }
    }

    /// Start a new internal node
    pub fn start_node(&mut self, kind: SyntaxKind) {
        self.stack.push((kind, Vec::new()));
    }

    /// Start a new node at a previously saved marker position.
    /// This effectively wraps all nodes parsed since the marker was created
    /// into a new parent node.
    pub fn start_node_at(&mut self, marker: Marker, kind: SyntaxKind) {
        if let Some((_, children)) = self.stack.last_mut() {
            // Extract children from marker position onwards
            let wrapped_children: Vec<_> = children.drain(marker.pos..).collect();
            // Push new node with those children
            self.stack.push((kind, wrapped_children));
        } else {
            // At root level, just start a new node
            self.stack.push((kind, Vec::new()));
        }
    }

    /// Add a token as a child
    pub fn add_token(&mut self, token_index: usize, width: usize) {
        let token_id = self.arena.alloc_token(token_index, width);
        if let Some((_, children)) = self.stack.last_mut() {
            children.push(token_id);
        }
    }

    /// Finish the current node and add it to its parent
    pub fn finish_node(&mut self) -> Option<GreenNodeId> {
        if let Some((kind, children)) = self.stack.pop() {
            let node_id = self.arena.alloc_internal(kind, children);

            // Add to parent if exists
            if let Some((_, parent_children)) = self.stack.last_mut() {
                parent_children.push(node_id);
            }

            Some(node_id)
        } else {
            None
        }
    }

    /// Check if the builder is at the root level
    pub fn is_root(&self) -> bool {
        self.stack.len() <= 1
    }
}

impl Default for GreenTreeBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_green_node_token() {
        let mut arena = GreenNodeArena::new();
        let token_id = arena.alloc_token(0, 5);
        assert_eq!(arena.width(token_id), 5);
        assert_eq!(arena.kind(token_id), None);
    }

    #[test]
    fn test_green_node_internal() {
        let mut arena = GreenNodeArena::new();
        let token1 = arena.alloc_token(0, 5);
        let token2 = arena.alloc_token(1, 3);
        let internal = arena.alloc_internal(SyntaxKind::BinaryExpr, vec![token1, token2]);

        assert_eq!(arena.width(internal), 8);
        assert_eq!(arena.kind(internal), Some(SyntaxKind::BinaryExpr));
        assert_eq!(arena.children(internal).unwrap().len(), 2);
    }

    #[test]
    fn test_builder() {
        let mut builder = GreenTreeBuilder::new();

        builder.start_node(SyntaxKind::Program);
        builder.start_node(SyntaxKind::IntLiteral);
        builder.add_token(0, 2); // "42"
        builder.finish_node();
        let root_id = builder.finish_node().unwrap();

        let arena = builder.arena();
        assert_eq!(arena.kind(root_id), Some(SyntaxKind::Program));
        assert_eq!(arena.width(root_id), 2);
    }

    #[test]
    fn test_nested_nodes() {
        let mut builder = GreenTreeBuilder::new();

        builder.start_node(SyntaxKind::BinaryExpr);
        builder.add_token(0, 1); // "1"
        builder.add_token(1, 1); // "+"
        builder.add_token(2, 1); // "2"
        let node_id = builder.finish_node().unwrap();

        let arena = builder.arena();
        assert_eq!(arena.width(node_id), 3);
        assert_eq!(arena.children(node_id).unwrap().len(), 3);
    }
}