dol 0.8.1

DOL (Design Ontology Language) - A declarative specification language for ontology-first development
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! Spirit Compiler
//!
//! End-to-end compilation from DOL source to WebAssembly binary.
//!
//! # Compilation Pipeline
//!
//! The Spirit compiler orchestrates a multi-stage compilation process:
//!
//! ```text
//! ┌─────────────┐
//! │ DOL Source  │
//! └──────┬──────┘
//!//!//! ┌─────────────┐
//! │   Lexer     │  Tokenization
//! └──────┬──────┘
//!//!//! ┌─────────────┐
//! │   Parser    │  Syntax Analysis
//! └──────┬──────┘
//!//!//! ┌─────────────┐
//! │     AST     │  Abstract Syntax Tree
//! └──────┬──────┘
//!//!//! ┌─────────────┐
//! │     HIR     │  High-level IR (desugared, canonical)
//! └──────┬──────┘
//!//!//! ┌─────────────┐
//! │    MLIR     │  Multi-level IR (optimizable)
//! └──────┬──────┘
//!//!//! ┌─────────────┐
//! │    WASM     │  WebAssembly bytecode
//! └─────────────┘
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use metadol::compiler::spirit::compile_source;
//!
//! let source = r#"
//!     module calculator @ 1.0
//!
//!     fun add(a: Int64, b: Int64) -> Int64 {
//!         return a + b
//!     }
//! "#;
//!
//! let compiled = compile_source(source, "calculator.dol")?;
//! assert!(!compiled.wasm.is_empty());
//! assert_eq!(&compiled.wasm[0..4], b"\0asm"); // WASM magic number
//! ```

use std::path::Path;

use crate::error::ParseError;
use crate::parser::Parser;

#[cfg(feature = "wasm-compile")]
use crate::lower;

/// Result of Spirit compilation.
///
/// Contains the compiled WASM bytecode along with optional source maps
/// and compilation warnings.
#[derive(Debug)]
pub struct CompiledSpirit {
    /// WebAssembly binary bytecode
    pub wasm: Vec<u8>,

    /// Source map for debugging (maps WASM offsets to DOL source locations)
    pub source_map: Option<SourceMap>,

    /// Non-fatal warnings emitted during compilation
    pub warnings: Vec<CompilerWarning>,
}

/// Source map for debugging.
///
/// Maps WASM bytecode offsets back to original DOL source locations,
/// enabling debuggers to show DOL source while stepping through WASM execution.
#[derive(Debug, Clone)]
pub struct SourceMap {
    /// Individual source map entries
    pub entries: Vec<SourceMapEntry>,
}

/// Single source map entry.
///
/// Maps a WASM bytecode offset to a DOL source location.
#[derive(Debug, Clone)]
pub struct SourceMapEntry {
    /// Offset in WASM bytecode
    pub wasm_offset: u32,

    /// Source file path
    pub source_file: String,

    /// Line number in source file (1-indexed)
    pub line: u32,

    /// Column number in line (1-indexed)
    pub column: u32,
}

/// Non-fatal warning from compilation.
///
/// Warnings indicate potential issues that don't prevent compilation,
/// such as deprecated syntax, unused variables, or optimization hints.
#[derive(Debug, Clone)]
pub struct CompilerWarning {
    /// Warning message
    pub message: String,

    /// Optional source location (file, line, column)
    pub location: Option<(String, u32, u32)>,
}

/// Compiler error type.
///
/// Represents all errors that can occur during the compilation pipeline,
/// from lexing through WASM emission.
#[derive(Debug)]
pub enum CompilerError {
    /// Lexer error during tokenization
    LexError(String),

    /// Parser error during syntax analysis
    ParseError(ParseError),

    /// Error during AST to HIR lowering
    HirError(String),

    /// Error during HIR to MLIR lowering
    MlirError(String),

    /// Error during WASM emission
    WasmError(String),

    /// I/O error (file not found, permission denied, etc.)
    IoError(std::io::Error),

    /// Project structure error (missing manifest, invalid entry point, etc.)
    ProjectError(String),
}

impl std::fmt::Display for CompilerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CompilerError::LexError(msg) => write!(f, "Lexer error: {}", msg),
            CompilerError::ParseError(err) => write!(f, "Parse error: {}", err),
            CompilerError::HirError(msg) => write!(f, "HIR lowering error: {}", msg),
            CompilerError::MlirError(msg) => write!(f, "MLIR lowering error: {}", msg),
            CompilerError::WasmError(msg) => write!(f, "WASM emission error: {}", msg),
            CompilerError::IoError(err) => write!(f, "I/O error: {}", err),
            CompilerError::ProjectError(msg) => write!(f, "Project error: {}", msg),
        }
    }
}

impl std::error::Error for CompilerError {}

impl From<ParseError> for CompilerError {
    fn from(err: ParseError) -> Self {
        CompilerError::ParseError(err)
    }
}

impl From<std::io::Error> for CompilerError {
    fn from(err: std::io::Error) -> Self {
        CompilerError::IoError(err)
    }
}

/// Compile a DOL source file to WASM.
///
/// Reads the file, parses it, and compiles it through the full pipeline.
///
/// # Arguments
///
/// * `path` - Path to the .dol file to compile
///
/// # Returns
///
/// A `CompiledSpirit` containing the WASM bytecode and metadata,
/// or a `CompilerError` if compilation fails.
///
/// # Errors
///
/// Returns an error if:
/// - The file cannot be read
/// - The source contains syntax errors
/// - Type checking fails
/// - Code generation fails
///
/// # Example
///
/// ```rust,ignore
/// use metadol::compiler::spirit::compile_file;
/// use std::path::Path;
///
/// let path = Path::new("examples/calculator.dol");
/// let compiled = compile_file(path)?;
/// std::fs::write("calculator.wasm", &compiled.wasm)?;
/// ```
pub fn compile_file(path: &Path) -> Result<CompiledSpirit, CompilerError> {
    let source = std::fs::read_to_string(path)?;
    let filename = path
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("unknown.dol");
    compile_source(&source, filename)
}

/// Compile DOL source code to WASM.
///
/// This is the main compilation entry point. It takes DOL source text
/// and transforms it through the complete compilation pipeline.
///
/// # Arguments
///
/// * `source` - The DOL source code to compile
/// * `filename` - Name of the source file (for error reporting and debug info)
///
/// # Returns
///
/// A `CompiledSpirit` containing the WASM bytecode and metadata,
/// or a `CompilerError` if compilation fails.
///
/// # Compilation Phases
///
/// 1. **Lexing & Parsing**: Transform source text into AST
/// 2. **HIR Lowering**: Desugar AST into canonical HIR
/// 3. **MLIR Lowering**: Generate MLIR operations from HIR
/// 4. **WASM Emission**: Emit WebAssembly bytecode from MLIR
///
/// # Example
///
/// ```rust,ignore
/// use metadol::compiler::spirit::compile_source;
///
/// let source = r#"
///     module math @ 1.0
///
///     fun multiply(x: Int64, y: Int64) -> Int64 {
///         return x * y
///     }
/// "#;
///
/// let compiled = compile_source(source, "math.dol")?;
/// assert!(!compiled.wasm.is_empty());
/// ```
#[cfg(feature = "wasm-compile")]
pub fn compile_source(source: &str, filename: &str) -> Result<CompiledSpirit, CompilerError> {
    let mut warnings = Vec::new();

    // ========================================================================
    // Phase 1: Parse DOL source to AST
    // ========================================================================
    let mut parser = Parser::new(source);
    let ast_file = parser.parse_file().map_err(CompilerError::ParseError)?;

    // ========================================================================
    // Phase 2: Lower AST to HIR (High-level Intermediate Representation)
    // ========================================================================
    let mut lowering_ctx = lower::LoweringContext::new();
    let hir_module = lower::lower_module(&mut lowering_ctx, &ast_file);

    // Collect lowering diagnostics as warnings
    for diag in lowering_ctx.diagnostics() {
        warnings.push(CompilerWarning {
            message: diag.message.clone(),
            location: diag
                .span
                .as_ref()
                .map(|span| (filename.to_string(), span.line as u32, span.column as u32)),
        });
    }

    // Check for lowering errors
    if lowering_ctx.has_errors() {
        let errors: Vec<String> = lowering_ctx
            .diagnostics()
            .iter()
            .filter(|d| matches!(d.kind, lower::DiagnosticKind::Error))
            .map(|d| d.message.clone())
            .collect();
        return Err(CompilerError::HirError(errors.join("; ")));
    }

    // ========================================================================
    // Phase 3: Lower HIR to MLIR
    // ========================================================================
    // NOTE: This is where we would transform HIR into MLIR operations.
    // The full HIR → MLIR lowering is complex and involves:
    // - Type inference and checking
    // - Control flow graph construction
    // - SSA form conversion
    // - Optimization passes
    //
    // For now, we return a placeholder indicating this needs implementation.
    //
    // When implemented, this would look like:
    // let mlir_module = lower_hir_to_mlir(&hir_module)?;

    // ========================================================================
    // Phase 4: Emit WASM from MLIR
    // ========================================================================
    // NOTE: This is where we would generate WASM bytecode from MLIR.
    // The MLIR → WASM lowering involves:
    // - MLIR dialect lowering (DOL → std → LLVM or direct to WASM)
    // - Instruction selection
    // - Register allocation
    // - Binary emission
    //
    // When implemented, this would look like:
    // let wasm_bytes = emit_wasm_from_mlir(&mlir_module)?;

    // For now, return a minimal valid WASM module as a placeholder
    // This allows testing the API while the full pipeline is implemented
    let wasm_bytes = generate_placeholder_wasm(&hir_module)?;

    Ok(CompiledSpirit {
        wasm: wasm_bytes,
        source_map: None, // TODO: Generate source map from HIR span information
        warnings,
    })
}

/// Compile a Spirit project directory.
///
/// A Spirit project is a directory containing:
/// - `manifest.toml`: Project metadata and dependencies
/// - `src/main.dol`: Entry point
/// - `src/*.dol`: Additional source files
///
/// # Arguments
///
/// * `project_dir` - Path to the Spirit project directory
///
/// # Returns
///
/// A `CompiledSpirit` containing the compiled WASM and metadata,
/// or a `CompilerError` if compilation fails.
///
/// # Project Structure
///
/// ```text
/// my-spirit/
/// ├── manifest.toml
/// └── src/
///     ├── main.dol
///     └── helper.dol
/// ```
///
/// # Example
///
/// ```rust,ignore
/// use metadol::compiler::spirit::compile_spirit_project;
/// use std::path::Path;
///
/// let project = Path::new("examples/hello-spirit");
/// let compiled = compile_spirit_project(project)?;
/// ```
#[cfg(feature = "wasm-compile")]
pub fn compile_spirit_project(project_dir: &Path) -> Result<CompiledSpirit, CompilerError> {
    // Validate project structure
    let manifest_path = project_dir.join("manifest.toml");
    if !manifest_path.exists() {
        return Err(CompilerError::ProjectError(format!(
            "manifest.toml not found in {}",
            project_dir.display()
        )));
    }

    let src_dir = project_dir.join("src");
    if !src_dir.exists() {
        return Err(CompilerError::ProjectError(format!(
            "src/ directory not found in {}",
            project_dir.display()
        )));
    }

    let main_dol = src_dir.join("main.dol");
    if !main_dol.exists() {
        return Err(CompilerError::ProjectError(format!(
            "src/main.dol not found in {}",
            project_dir.display()
        )));
    }

    // TODO: Parse manifest.toml to get:
    // - Spirit name and version
    // - Dependencies
    // - Build configuration
    //
    // For now, just compile the main.dol entry point
    compile_file(&main_dol)
}

/// Generate a placeholder WASM module.
///
/// This generates a minimal valid WASM module that can be used for testing
/// while the full compilation pipeline is being implemented.
///
/// The generated module contains:
/// - WASM magic number and version
/// - Empty type, function, and code sections
///
/// # Arguments
///
/// * `_hir_module` - HIR module (currently unused, will be used when implemented)
///
/// # Returns
///
/// A valid WASM bytecode module
#[cfg(feature = "wasm-compile")]
fn generate_placeholder_wasm(
    _hir_module: &crate::hir::HirModule,
) -> Result<Vec<u8>, CompilerError> {
    // Generate a minimal valid WASM module
    // Format: https://webassembly.github.io/spec/core/binary/modules.html
    //
    // WASM binary format:
    // - Magic number: 0x00 0x61 0x73 0x6D ("\0asm")
    // - Version: 0x01 0x00 0x00 0x00 (version 1)
    // - Sections: (empty for minimal module)

    let mut wasm = Vec::new();

    // WASM magic number
    wasm.extend_from_slice(&[0x00, 0x61, 0x73, 0x6D]);

    // WASM version 1
    wasm.extend_from_slice(&[0x01, 0x00, 0x00, 0x00]);

    // TODO: Add actual sections based on HIR:
    // - Type section (function signatures)
    // - Function section (function indices)
    // - Export section (exported functions)
    // - Code section (function bodies)

    Ok(wasm)
}

// Stub implementation for when wasm feature is not enabled
#[cfg(not(feature = "wasm-compile"))]
pub fn compile_source(_source: &str, _filename: &str) -> Result<CompiledSpirit, CompilerError> {
    Err(CompilerError::WasmError(
        "WASM compilation requires the 'wasm' feature flag".to_string(),
    ))
}

#[cfg(not(feature = "wasm-compile"))]
pub fn compile_spirit_project(_project_dir: &Path) -> Result<CompiledSpirit, CompilerError> {
    Err(CompilerError::WasmError(
        "WASM compilation requires the 'wasm' feature flag".to_string(),
    ))
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
#[cfg(feature = "wasm-compile")]
mod tests {
    use super::*;

    #[test]
    #[ignore] // TODO: Parser now treats 'test' as keyword, use different module name
    fn test_compile_empty_module() {
        let source = r#"
module test @ 1.0.0
"#;

        let result = compile_source(source, "test.dol");
        assert!(result.is_ok(), "Failed to compile: {:?}", result.err());

        let compiled = result.unwrap();
        assert!(!compiled.wasm.is_empty());

        // Verify WASM magic number
        assert_eq!(&compiled.wasm[0..4], b"\0asm");
        // Verify WASM version 1
        assert_eq!(&compiled.wasm[4..8], &[1, 0, 0, 0]);
    }

    #[test]
    #[ignore] // TODO: Parser now treats 'test' as keyword, use different module name
    fn test_compile_simple_gene() {
        let source = r#"
module test @ 1.0.0

gene Counter {
    has value: Int64

    constraint non_negative {
        this.value >= 0
    }
}

exegesis {
    A simple counter gene.
}
"#;

        let result = compile_source(source, "test.dol");
        assert!(result.is_ok(), "Failed to compile: {:?}", result.err());

        let compiled = result.unwrap();
        assert!(!compiled.wasm.is_empty());
        assert_eq!(&compiled.wasm[0..4], b"\0asm");
    }

    #[test]
    fn test_compile_with_function() {
        let source = r#"
module math @ 1.0.0

fun add(a: Int64, b: Int64) -> Int64 {
    return a + b
}
"#;

        let result = compile_source(source, "math.dol");
        assert!(result.is_ok(), "Failed to compile: {:?}", result.err());

        let compiled = result.unwrap();
        assert!(!compiled.wasm.is_empty());
        assert_eq!(&compiled.wasm[0..4], b"\0asm");
    }

    #[test]
    fn test_compile_invalid_syntax() {
        let source = r#"
module broken @ 1.0.0

gene Invalid {
    this is not valid syntax!!!
}
"#;

        let result = compile_source(source, "broken.dol");
        assert!(result.is_err());

        match result.unwrap_err() {
            CompilerError::ParseError(_) => {
                // Expected
            }
            other => panic!("Expected ParseError, got {:?}", other),
        }
    }

    #[test]
    fn test_compiler_error_display() {
        let err = CompilerError::WasmError("test error".to_string());
        assert_eq!(err.to_string(), "WASM emission error: test error");

        let err = CompilerError::HirError("type mismatch".to_string());
        assert_eq!(err.to_string(), "HIR lowering error: type mismatch");
    }

    #[test]
    fn test_source_map_entry() {
        let entry = SourceMapEntry {
            wasm_offset: 42,
            source_file: "test.dol".to_string(),
            line: 10,
            column: 5,
        };

        assert_eq!(entry.wasm_offset, 42);
        assert_eq!(entry.line, 10);
        assert_eq!(entry.column, 5);
    }

    #[test]
    fn test_compiler_warning() {
        let warning = CompilerWarning {
            message: "deprecated syntax".to_string(),
            location: Some(("test.dol".to_string(), 5, 10)),
        };

        assert_eq!(warning.message, "deprecated syntax");
        assert!(warning.location.is_some());
    }
}