lambdust 0.1.1

A Scheme dialect with gradual typing and effect systems
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
//! The main macro expander.

use crate::ast::{Expr, Spanned};
use crate::diagnostics::{Error, Result, Span};
use crate::eval::Environment;
use super::{
    MacroTransformer, MacroEnvironment, HygieneContext, PatternBindings,
    install_builtin_macros, next_hygiene_id, parse_syntax_rules, syntax_rules_to_macro_transformer
};
use std::collections::HashMap;
use std::rc::Rc;

/// The main macro expander.
#[derive(Debug, Clone)]
pub struct MacroExpander {
    /// Environment containing macro definitions
    macro_env: Rc<MacroEnvironment>,
    /// Current expansion depth (for detecting infinite recursion)
    expansion_depth: usize,
    /// Maximum allowed expansion depth
    max_expansion_depth: usize,
    /// Current hygiene context
    hygiene_context: HygieneContext,
}

// SAFETY: MacroExpander is designed to be used in a thread-safe context through
// external synchronization (Mutex). While it contains Rc and RefCell internally,
// these are only accessed through synchronized methods, ensuring thread safety.
// The macro expansion system is coordinated by the GC integration layer which
// ensures proper synchronization.
unsafe impl Send for MacroExpander {}
unsafe impl Sync for MacroExpander {}

impl MacroExpander {
    /// Creates a new macro expander.
    pub fn new() -> Self {
        Self {
            macro_env: Rc::new(MacroEnvironment::new()),
            expansion_depth: 0,
            max_expansion_depth: 100,
            hygiene_context: HygieneContext::new(),
        }
    }
    
    /// Ensures that the macro expander can access global syntax elements.
    /// This is crucial for macros that expand to basic special forms like 'lambda', 'if', etc.
    fn ensure_global_syntax_access(&mut self) {
        // Currently, we rely on the global environment binding special forms as symbols
        // This allows macro templates to reference them properly during expansion
        // The actual binding happens in create_global_environment() 
        // where bind_special_forms_as_identifiers() is called
        
        // For now, we just ensure the macro environment is properly initialized
        // Future enhancement: could create a dedicated macro-time environment
        // that has explicit mappings for special forms
    }

    /// Creates a new macro expander with built-in macros.
    pub fn with_builtins() -> Self {
        let mut expander = Self::new();
        
        // Initialize macro environment with access to global environment
        // This ensures macros can reference basic syntax like 'lambda', 'if', etc.
        expander.ensure_global_syntax_access();
        
        install_builtin_macros(&mut expander);
        expander
    }

    /// Expands a single expression.
    pub fn expand(&mut self, expr: &Spanned<Expr>) -> Result<Spanned<Expr>> {
        self.expand_inner(expr, &mut Vec::new())
    }
    
    /// Expands all expressions in a program.
    pub fn expand_program(&mut self, program: &crate::ast::Program) -> Result<crate::ast::Program> {
        let mut expanded_expressions = Vec::new();
        for expr in &program.expressions {
            let expanded = self.expand(expr)?;
            expanded_expressions.push(expanded);
        }
        Ok(crate::ast::Program::with_expressions(expanded_expressions))
    }

    /// Internal expansion method with recursion tracking.
    fn expand_inner(
        &mut self,
        expr: &Spanned<Expr>,
        expansion_trail: &mut Vec<String>,
    ) -> Result<Spanned<Expr>> {
        // Check for infinite recursion
        if self.expansion_depth >= self.max_expansion_depth {
            return Err(Box::new(Error::macro_error(
                "Macro expansion depth exceeded".to_string(),
                expr.span,
            )));
        }

        match &expr.inner {
            Expr::Application { operator, operands } => {
                // Check if the operator is a macro
                if let Expr::Identifier(name) = &operator.inner {
                    if let Some(transformer) = self.macro_env.lookup(name) {
                        // Prevent infinite recursion
                        if expansion_trail.contains(name) {
                            return Err(Box::new(Error::macro_error(
                                format!("Recursive macro expansion detected: {name}"),
                                expr.span,
                            )));
                        }

                        expansion_trail.push(name.clone());
                        self.expansion_depth += 1;

                        let result = self.expand_macro(&transformer, operands, expr.span);

                        self.expansion_depth -= 1;
                        expansion_trail.pop();

                        // Recursively expand the result
                        match result {
                            Ok(expanded) => self.expand_inner(&expanded, expansion_trail),
                            Err(e) => Err(e),
                        }
                    } else {
                        // Not a macro, expand operands
                        self.expand_application(operator, operands, expr.span)
                    }
                } else {
                    // Operator is not an identifier, expand normally
                    self.expand_application(operator, operands, expr.span)
                }
            }
            // Special forms that contain expressions to expand
            Expr::Lambda { formals, metadata, body } => {
                let expanded_body = self.expand_body(body)?;
                let expanded_metadata = self.expand_metadata(metadata)?;
                Ok(Spanned::new(
                    Expr::Lambda {
                        formals: formals.clone(),
                        metadata: expanded_metadata,
                        body: expanded_body,
                    },
                    expr.span,
                ))
            }
            Expr::If { test, consequent, alternative } => {
                let expanded_test = self.expand_inner(test, expansion_trail)?;
                let expanded_consequent = self.expand_inner(consequent, expansion_trail)?;
                let expanded_alternative = if let Some(alt) = alternative {
                    Some(Box::new(self.expand_inner(alt, expansion_trail)?))
                } else {
                    None
                };
                Ok(Spanned::new(
                    Expr::If {
                        test: Box::new(expanded_test),
                        consequent: Box::new(expanded_consequent),
                        alternative: expanded_alternative,
                    },
                    expr.span,
                ))
            }
            Expr::Define { name, value, metadata } => {
                let expanded_value = self.expand_inner(value, expansion_trail)?;
                let expanded_metadata = self.expand_metadata(metadata)?;
                Ok(Spanned::new(
                    Expr::Define {
                        name: name.clone(),
                        value: Box::new(expanded_value),
                        metadata: expanded_metadata,
                    },
                    expr.span,
                ))
            }
            Expr::DefineSyntax { name: _, transformer: _ } => {
                // Define-syntax should not be expanded by the macro expander
                // It should be handled directly by the evaluator
                Ok(expr.clone())
            }
            Expr::SyntaxRules { literals, rules } => {
                // syntax-rules should not appear at top level normally, but handle it
                // Convert to macro transformer representation
                let syntax_rules_transformer = super::parse_syntax_rules(expr, Rc::new(Environment::new(None, 0)))?;
                let macro_transformer = super::syntax_rules_to_macro_transformer(syntax_rules_transformer);
                
                // For demonstration, create a temporary identifier
                let temp_name = format!("temp-syntax-{}", next_hygiene_id());
                self.macro_env.define(temp_name, macro_transformer);
                Ok(Spanned::new(Expr::Begin(vec![]), expr.span)) // Expand to empty begin
            }
            // Other expression types that don't need expansion
            _ => Ok(expr.clone()),
        }
    }

    /// Expands a macro application.
    fn expand_macro(
        &mut self,
        transformer: &MacroTransformer,
        operands: &[Spanned<Expr>],
        span: Span,
    ) -> Result<Spanned<Expr>> {
        // Create input expression for pattern matching
        let input_expr = Spanned::new(
            Expr::Application {
                operator: Box::new(Spanned::new(
                    Expr::Identifier(transformer.name.clone().unwrap_or_else(|| "anonymous-macro".to_string())),
                    span,
                )),
                operands: operands.to_vec(),
            },
            span,
        );

        // Try to match the pattern against the input
        let bindings = self.match_pattern(&transformer.pattern, &input_expr)?;

        // Expand the template with the bindings
        let expanded = self.expand_template(&transformer.template, &bindings, span)?;

        // Apply hygiene transformations
        self.apply_hygiene(expanded, &transformer.definition_env)
    }

    /// Expands a function application (non-macro).
    fn expand_application(
        &mut self,
        operator: &Spanned<Expr>,
        operands: &[Spanned<Expr>],
        span: Span,
    ) -> Result<Spanned<Expr>> {
        let expanded_operator = self.expand_inner(operator, &mut Vec::new())?;
        let mut expanded_operands = Vec::new();
        for operand in operands {
            expanded_operands.push(self.expand_inner(operand, &mut Vec::new())?);
        }
        Ok(Spanned::new(
            Expr::Application {
                operator: Box::new(expanded_operator),
                operands: expanded_operands,
            },
            span,
        ))
    }

    /// Expands a sequence of expressions.
    fn expand_body(&mut self, body: &[Spanned<Expr>]) -> Result<Vec<Spanned<Expr>>> {
        let mut expanded = Vec::new();
        for expr in body {
            expanded.push(self.expand_inner(expr, &mut Vec::new())?);
        }
        Ok(expanded)
    }

    /// Expands metadata expressions.
    fn expand_metadata(
        &mut self,
        metadata: &HashMap<String, Spanned<Expr>>,
    ) -> Result<HashMap<String, Spanned<Expr>>> {
        let mut expanded = HashMap::new();
        for (key, value) in metadata {
            expanded.insert(key.clone(), self.expand_inner(value, &mut Vec::new())?);
        }
        Ok(expanded)
    }

    /// Evaluates a macro transformer expression.
    fn evaluate_transformer(&self, transformer_expr: &Spanned<Expr>, _expansion_trail: Vec<String>) -> Result<MacroTransformer> {
        
        // Check if this is a syntax-rules form (as application)
        if let Expr::Application { operator, .. } = &transformer_expr.inner {
            if let Expr::Identifier(name) = &operator.inner {
                if name == "syntax-rules" {
                    // Parse syntax-rules and convert to MacroTransformer
                    // For now, create a basic environment - this will be improved when
                    // macro/evaluator integration is complete
                    let empty_env = Rc::new(Environment::new(None, 0));
                    let syntax_rules = parse_syntax_rules(
                        transformer_expr,
                        empty_env,
                    )?;
                    return Ok(syntax_rules_to_macro_transformer(syntax_rules));
                }
            }
        }
        
        // Check if this is a direct SyntaxRules expression
        if let Expr::SyntaxRules { literals, rules } = &transformer_expr.inner {
            // Handle SyntaxRules directly without going through parse_syntax_rules
            // Create the transformer directly from the parsed structure
            let definition_env = Rc::new(Environment::new(None, 0));
            
            // Convert the parsed rules to SyntaxRule structures
            let mut syntax_rules = Vec::new();
            for (pattern_expr, template_expr) in rules {
                // Each rule is a (pattern, template) pair
                let pattern = Self::expr_to_pattern(pattern_expr)?;
                let template = Self::expr_to_template(template_expr)?;
                
                syntax_rules.push(crate::macro_system::syntax_rules::SyntaxRule {
                    pattern,
                    template,
                });
            }
            
            let transformer = crate::macro_system::SyntaxRulesTransformer {
                literals: literals.clone(),
                rules: syntax_rules,
                name: None,
                definition_env,
                custom_ellipsis: None,
                srfi_149_mode: true, // Enable SRFI-149 by default
            };
            
            return Ok(syntax_rules_to_macro_transformer(transformer));
        }
        
        Err(Box::new(Error::macro_error(
            format!("Expected syntax-rules transformer, got {:?}", transformer_expr.inner),
            transformer_expr.span,
        )))
    }

    
    /// Converts an expression to a pattern.
    fn expr_to_pattern(expr: &Spanned<Expr>) -> Result<crate::macro_system::Pattern> {
        match &expr.inner {
            Expr::Identifier(name) => Ok(crate::macro_system::Pattern::identifier(name)),
            Expr::Application { operator, operands } => {
                let op_pattern = Self::expr_to_pattern(operator)?;
                let mut arg_patterns = Vec::new();
                for arg in operands {
                    arg_patterns.push(Self::expr_to_pattern(arg)?);
                }
                let mut patterns = vec![op_pattern];
                patterns.extend(arg_patterns);
                Ok(crate::macro_system::Pattern::list(patterns))
            }
            Expr::Literal(lit) => Ok(crate::macro_system::Pattern::literal(lit.clone())),
            _ => {
                // Fallback to variable pattern
                Ok(crate::macro_system::Pattern::variable("_"))
            }
        }
    }
    
    /// Converts an expression to a template.
    fn expr_to_template(expr: &Spanned<Expr>) -> Result<crate::macro_system::Template> {
        match &expr.inner {
            Expr::Identifier(name) => Ok(crate::macro_system::Template::identifier(name)),
            Expr::Application { operator, operands } => {
                let op_template = Self::expr_to_template(operator)?;
                let mut arg_templates = Vec::new();
                for arg in operands {
                    arg_templates.push(Self::expr_to_template(arg)?);
                }
                let mut templates = vec![op_template];
                templates.extend(arg_templates);
                Ok(crate::macro_system::Template::list(templates))
            }
            Expr::Literal(lit) => Ok(crate::macro_system::Template::literal(lit.clone())),
            _ => {
                // Fallback to identifier template
                Ok(crate::macro_system::Template::identifier("unknown"))
            }
        }
    }

    /// Matches a pattern against an expression.
    fn match_pattern(
        &self,
        pattern: &super::Pattern,
        expr: &Spanned<Expr>,
    ) -> Result<PatternBindings> {
        pattern.match_expr(expr)
    }

    /// Expands a template with the given bindings.
    fn expand_template(
        &self,
        template: &super::Template,
        bindings: &PatternBindings,
        span: Span,
    ) -> Result<Spanned<Expr>> {
        template.expand(bindings, span)
    }

    /// Applies hygiene transformations to ensure lexical scoping.
    fn apply_hygiene(
        &mut self,
        expr: Spanned<Expr>,
        definition_env: &Environment,
    ) -> Result<Spanned<Expr>> {
        self.hygiene_context.rename_identifiers(expr, definition_env)
    }

    /// Defines a new macro.
    pub fn define_macro(&mut self, name: String, transformer: MacroTransformer) {
        self.macro_env.define(name, transformer);
    }
    
    /// Defines a syntax-rules macro directly.
    pub fn define_syntax_rules_macro(&mut self, name: String, syntax_rules: crate::macro_system::SyntaxRulesTransformer) {
        let transformer = crate::macro_system::syntax_rules_to_macro_transformer(syntax_rules);
        self.macro_env.define(name, transformer);
    }

    /// Gets the macro environment.
    pub fn macro_env(&self) -> &MacroEnvironment {
        &self.macro_env
    }

}

impl Default for MacroExpander {
    fn default() -> Self {
        Self::with_builtins()
    }
}