microcad-lang 0.5.0

µcad language
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
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
// Copyright © 2024-2026 The µcad authors <info@microcad.xyz>
// SPDX-License-Identifier: AGPL-3.0-or-later

use microcad_core::hash::HashSet;
use microcad_lang_base::{
    Diag, DiagHandler, DiagResult, Diagnostic, FormatTree, GetSourceLocInfoByHash, HashId, Output,
    PushDiag, SourceLocInfo, SrcReferrer, TreeDisplay, TreeState,
};

use crate::{
    builtin::*,
    eval::*,
    lower::{SingleIdentifier, ir},
    model::*,
    symbol::SymbolDef,
};

/// *Context* for *evaluation* of a resolved µcad file.
///
/// The context is used to store the current state of the evaluation.
pub struct EvalContext {
    /// Symbol table
    pub root: Symbol,
    /// Source cache
    sources: Sources,
    /// Stack of currently opened scopes with symbols while evaluation.
    pub(super) stack: Stack,
    /// Output channel for [__builtin::print].
    output: Box<dyn Output>,
    /// Exporter registry.
    exporters: ExporterRegistry,
    /// Importer registry.
    importers: ImporterRegistry,
    /// Diagnostics handler.
    pub diag: DiagHandler,
}

impl EvalContext {
    /// Create a new context from a resolved symbol table.
    pub fn new(
        resolve_context: ResolveContext,
        output: Box<dyn Output>,
        exporters: ExporterRegistry,
        importers: ImporterRegistry,
    ) -> Self {
        log::debug!("Creating evaluation context");

        Self {
            root: resolve_context.root,
            sources: resolve_context.sources,
            diag: resolve_context.diag,
            output,
            exporters,
            importers,
            stack: Stack::default(),
        }
    }

    /// Current symbol, panics if there no current symbol.
    pub(crate) fn current_symbol(&self) -> Option<Symbol> {
        self.stack.current_symbol()
    }

    /// Create a new context from a source file.
    pub fn from_source(
        root: std::rc::Rc<ir::Source>,
        builtin: Option<Symbol>,
        search_paths: Vec<std::path::PathBuf>,
        output: Box<dyn Output>,
        exporters: ExporterRegistry,
        importers: ImporterRegistry,
    ) -> EvalResult<Self> {
        Ok(Self::new(
            ResolveContext::create(root, search_paths, builtin, DiagHandler::default())?,
            output,
            exporters,
            importers,
        ))
    }

    /// Access captured output.
    pub fn output(&self) -> Option<String> {
        self.output.output()
    }

    /// Print for `__builtin::print`.
    pub fn print(&mut self, what: String) {
        self.output.print(what).expect("could not write to output");
    }

    /// Evaluate context into a value.
    pub fn eval(&mut self) -> EvalResult<Model> {
        if self.diag.error_count() > 0 {
            log::error!("Aborting evaluation because of prior resolve errors!");
            return Err(EvalError::ResolveFailed.into());
        }
        let model: Model = self.sources.root().eval(self)?;
        log::trace!("Post-evaluation context:\n{self:?}");
        log::trace!("Evaluated Model:\n{}", FormatTree(&model));

        let unused = self
            .root
            .unused_private()
            .iter()
            .map(|symbol| {
                (
                    match self.sources.get_code(&symbol) {
                        Ok(id) => id,
                        Err(_) => symbol.id().to_string(),
                    },
                    symbol.src_ref(),
                )
            })
            // intermediate hasp storage to avoid duplicates
            .collect::<indexmap::IndexMap<_, _>>();

        unused.into_iter().try_for_each(|(id, src_ref)| {
            self.warning(&src_ref, EvalError::UnusedGlobalSymbol(id))
        })?;

       
       Ok(model)
    }

    /// Run the closure `f` within the given `stack_frame`.
    pub(super) fn scope<T>(
        &mut self,
        stack_frame: StackFrame,
        f: impl FnOnce(&mut EvalContext) -> T,
    ) -> T {
        self.open(stack_frame);
        let result = f(self);
        let mut unused: Vec<_> = if let Some(frame) = &self.stack.current_frame() {
            if let Some(locals) = frame.locals() {
                locals
                    .iter()
                    .filter(|(_, symbol)| !symbol.is_used())
                    .filter(|(id, _)| !id.ignore())
                    .filter(|(_, symbol)| !symbol.src_ref().is_none())
                    .map(|(id, _)| id.clone())
                    .collect()
            } else {
                vec![]
            }
        } else {
            vec![]
        };
        unused.sort();

        unused
            .iter()
            .try_for_each(|id| self.warning(id, EvalError::UnusedLocal(id.clone())))
            .expect("diag error");

        self.close();
        result
    }

    /// All registered exporters.
    pub fn exporters(&self) -> &ExporterRegistry {
        &self.exporters
    }

    /// Return search paths of this context.
    pub fn search_paths(&self) -> &Vec<std::path::PathBuf> {
        self.sources.search_paths()
    }

    /// Get property from current model.
    pub(super) fn get_property(&self, id: &Identifier) -> EvalResult<Value> {
        match self.get_model() {
            Ok(model) => {
                if let Some(value) = model.get_property(id) {
                    Ok(value.clone())
                } else {
                    Err(EvalError::PropertyNotFound(id.clone()).into())
                }
            }
            Err(err) => Err(err),
        }
    }

    /// Initialize a property.
    ///
    /// Returns error if there is no model or the property has been initialized before.
    pub(super) fn init_property(&self, id: Identifier, value: Value) -> EvalResult<()> {
        match self.get_model() {
            Ok(model) => {
                if let Some(previous_value) = model.borrow_mut().set_property(id.clone(), value) {
                    if !previous_value.is_invalid() {
                        return Err(EvalError::ValueAlreadyDefined {
                            location: id.src_ref(),
                            name: id.clone(),
                            value: previous_value.to_string(),
                            previous_location: id.src_ref(),
                        }
                        .into());
                    }
                }
                Ok(())
            }
            Err(err) => Err(err),
        }
    }

    /// Return if the current frame is an init frame.
    pub(super) fn is_init(&mut self) -> bool {
        matches!(self.stack.current_frame(), Some(StackFrame::Init(_)))
    }

    /// Lookup a property by qualified name.
    fn lookup_property(&self, name: &ir::QualifiedName) -> EvalResult<Symbol> {
        log::trace!(
            "{lookup} for property {name:?}",
            lookup = microcad_lang_base::mark!(LOOKUP)
        );

        if self.stack.current_call_name().is_some() {
            if let Some(id) = name.single_identifier() {
                match self.get_property(id) {
                    Ok(value) => {
                        log::trace!(
                            "{found} property '{name:?}'",
                            found = microcad_lang_base::mark!(FOUND)
                        );
                        return Ok(Symbol::new(SymbolDef::Value(id.clone(), value), None));
                    }
                    Err(err) => return Err(err),
                }
            }
        }
        log::trace!(
            "{not_found} Property '{name:?}'",
            not_found = microcad_lang_base::mark!(NOT_FOUND)
        );
        Err(EvalError::NoPropertyId(name.clone()).into())
    }

    fn lookup_workbench(
        &self,
        name: &ir::QualifiedName,
        target: LookupTarget,
    ) -> ResolveResult<Symbol> {
        if let Some(workbench) = &self.stack.current_call_name() {
            log::trace!(
                "{lookup} for symbol '{name:?}' in current workbench '{workbench:?}'",
                lookup = microcad_lang_base::mark!(LOOKUP)
            );
            match self.root.lookup_within_name(name, workbench, target) {
                Ok(symbol) => {
                    log::trace!(
                        "{found} symbol in current module: {symbol:?}",
                        found = microcad_lang_base::mark!(FOUND),
                    );
                    Ok(symbol)
                }
                Err(err) => {
                    log::trace!(
                        "{not_found} symbol '{name:?}': {err}",
                        not_found = microcad_lang_base::mark!(NOT_FOUND)
                    );
                    Err(err)
                }
            }
        } else {
            log::trace!(
                "{not_found} No current workbench",
                not_found = microcad_lang_base::mark!(NOT_FOUND)
            );
            Err(ResolveError::SymbolNotFound(name.clone()))
        }
    }

    fn lookup_within(
        &self,
        name: &ir::QualifiedName,
        target: LookupTarget,
    ) -> ResolveResult<Symbol> {
        self.root.lookup_within(
            name,
            &self.root.search(&self.stack.current_module_name(), false)?,
            target,
        )
    }
}

impl Locals for EvalContext {
    fn set_local_value(&mut self, id: Identifier, value: Value) -> EvalResult<()> {
        self.stack.set_local_value(id, value)
    }

    fn get_local_value(&self, id: &Identifier) -> EvalResult<Value> {
        self.stack.get_local_value(id)
    }

    fn open(&mut self, frame: StackFrame) {
        self.stack.open(frame);
    }

    fn close(&mut self) -> StackFrame {
        self.stack.close()
    }

    fn fetch_symbol(&self, id: &Identifier) -> EvalResult<Symbol> {
        self.stack.fetch_symbol(id)
    }

    fn get_model(&self) -> EvalResult<Model> {
        self.stack.get_model()
    }

    fn current_name(&self) -> ir::QualifiedName {
        self.stack.current_name()
    }
}

impl Lookup<Box<EvalError>> for EvalContext {
    fn lookup(&self, name: &ir::QualifiedName, target: LookupTarget) -> EvalResult<Symbol> {
        log::debug!("Lookup {target} '{name:?}' (at line {:?}):", name.src_ref());

        log::trace!("- lookups -------------------------------------------------------");
        // collect all symbols that can be found and remember origin
        let results = [
            ("local", { self.stack.lookup(name, target) }),
            ("global", {
                self.lookup_within(name, target).map_err(|err| err.into())
            }),
            ("property", { self.lookup_property(name) }),
            ("workbench", {
                self.lookup_workbench(name, target)
                    .map_err(|err| err.into())
            }),
        ]
        .into_iter();

        log::trace!("- lookup results ------------------------------------------------");
        let results = results.inspect(|(from, result)| log::trace!("{from}: {:?}", result));

        // collect ok-results and ambiguity errors
        let (found, mut ambiguities, mut errors) = results.fold(
            (vec![], vec![], vec![]),
            |(mut oks, mut ambiguities, mut errors), (origin, result)| {
                match result {
                    Ok(symbol) => oks.push((origin, symbol)),
                    Err(err) => match *err {
                        EvalError::AmbiguousSymbol(ambiguous, others) => {
                            ambiguities.push((origin, EvalError::AmbiguousSymbol ( ambiguous, others )));
                        }                
                        // ignore all kinds of "not found" errors
                        EvalError::SymbolNotFound(_)
                        // for locals
                        | EvalError::LocalNotFound(_)
                        // for model property
                        | EvalError::NoModelInWorkbench
                        | EvalError::PropertyNotFound(_)
                        | EvalError::NoPropertyId(_)
                        // for symbol table
                        | EvalError::ResolveError(ResolveError::SymbolNotFound(_))
                        | EvalError::ResolveError(ResolveError::SymbolIsPrivate(_))
                        | EvalError::ResolveError(ResolveError::NulHash)
                        | EvalError::ResolveError(ResolveError::WrongTarget) => {},
                        err => errors.push((origin, err)),
                    }
                }
                (oks, ambiguities, errors)
            },
        );

        // log any unexpected errors and return early
        if !errors.is_empty() {
            log::error!("Unexpected errors while lookup symbol '{name:?}':");
            errors
                .iter()
                .for_each(|(origin, err)| log::error!("Lookup ({origin}) error: {err}"));

            return Err(errors.remove(0).1.into());
        }

        // early emit any ambiguity error
        if !ambiguities.is_empty() {
            log::debug!(
                "{ambiguous} Symbol '{name:?}':\n{}",
                ambiguities
                    .iter()
                    .map(|(origin, err)| format!("{origin}: {err}"))
                    .collect::<Vec<_>>()
                    .join("\n"),
                ambiguous = microcad_lang_base::mark!(AMBIGUOUS)
            );
            return Err(ambiguities.remove(0).1.into());
        }

        // filter by lookup target
        let found: Vec<_> = found
            .iter()
            .filter(|(_, symbol)| target.matches(symbol))
            .collect();

        // check for ambiguity in what's left
        match found.first() {
            Some((origin, symbol)) => {
                // check if all findings point to the same symbol
                if found.iter().all(|(_, x)| x == symbol) {
                    log::debug!(
                        "{found} symbol '{name:?}' in {origin}",
                        found = microcad_lang_base::mark!(FOUND!)
                    );
                    symbol.set_used();
                    Ok(symbol.clone())
                } else {
                    let others: ir::QualifiedNames =
                        found.iter().map(|(_, symbol)| symbol.full_name()).collect();
                    log::debug!(
                        "{ambiguous} symbol '{name:?}' in {others:?}:\n{self:?}",
                        ambiguous = microcad_lang_base::mark!(AMBIGUOUS),
                    );
                    Err(EvalError::AmbiguousSymbol(name.clone(), others).into())
                }
            }
            None => {
                log::debug!(
                    "{not_found} Symbol '{name:?}'",
                    not_found = microcad_lang_base::mark!(NOT_FOUND!)
                );
                Err(EvalError::SymbolNotFound(name.clone()).into())
            }
        }
    }

    fn ambiguity_error(ambiguous: ir::QualifiedName, others: ir::QualifiedNames) -> Box<EvalError> {
        EvalError::AmbiguousSymbol(ambiguous, others).into()
    }
}

impl microcad_lang_base::Diag for EvalContext {
    fn fmt_diagnosis(&self, f: &mut dyn std::fmt::Write) -> std::fmt::Result {
        self.diag.pretty_print(f, self)
    }

    fn warning_count(&self) -> u32 {
        self.diag.warning_count()
    }

    fn error_count(&self) -> u32 {
        self.diag.error_count()
    }

    fn error_lines(&self) -> HashSet<u32> {
        self.diag.error_lines()
    }

    fn warning_lines(&self) -> HashSet<u32> {
        self.diag.warning_lines()
    }
}

impl PushDiag for EvalContext {
    fn push_diag(&mut self, diag: Diagnostic) -> DiagResult<()> {
        self.diag.push_diag(diag)
    }
}

impl GetSourceByHash for EvalContext {
    fn get_by_hash(&self, hash: u64) -> ResolveResult<std::rc::Rc<ir::Source>> {
        self.sources.get_by_hash(hash)
    }
}

impl GetSourceLocInfoByHash for EvalContext {
    fn get_source_loc_info_by_hash(&'_ self, hash: HashId) -> Option<SourceLocInfo<'_>> {
        self.sources.get_source_loc_info_by_hash(hash)
    }
}

impl std::fmt::Debug for EvalContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Ok(model) = self.get_model() {
            write!(f, "\nModel:\n")?;
            model.tree_print(f, TreeState::new_debug(4))?;
        }
        writeln!(f, "\nCurrent: {:?}", self.stack.current_name())?;
        writeln!(f, "\nModule: {:?}", self.stack.current_module_name())?;
        write!(f, "\nLocals Stack:\n{:?}", self.stack)?;
        writeln!(f, "\nCall Stack:")?;
        self.stack.pretty_print_call_trace(f, &self.sources)?;

        writeln!(f, "\nSources:\n")?;
        write!(f, "{:?}", &self.sources)?;

        write!(f, "\nSymbol Table:\n")?;
        self.root.tree_print(f, TreeState::new_debug(0))?;

        match self.error_count() {
            0 => write!(f, "No errors")?,
            1 => write!(f, "1 error")?,
            _ => write!(f, "{} errors", self.error_count())?,
        };
        match self.warning_count() {
            0 => writeln!(
                f,
                ", no warnings{}",
                if self.error_count() > 0 { ":" } else { "." }
            )?,
            1 => writeln!(f, ", 1 warning:")?,
            _ => writeln!(f, ", {} warnings:", self.warning_count())?,
        };
        self.fmt_diagnosis(f)?;
        Ok(())
    }
}

impl ImporterRegistryAccess for EvalContext {
    type Error = Box<EvalError>;

    fn import(
        &mut self,
        arg_map: &Tuple,
        search_paths: &[std::path::PathBuf],
    ) -> Result<Value, Self::Error> {
        match self.importers.import(arg_map, search_paths) {
            Ok(value) => Ok(value),
            Err(err) => {
                self.error(arg_map, err)?;
                Ok(Value::None)
            }
        }
    }
}

impl ExporterAccess for EvalContext {
    fn exporter_by_id(&self, id: &crate::Id) -> Result<std::rc::Rc<dyn Exporter>, ExportError> {
        self.exporters.exporter_by_id(id)
    }

    fn exporter_by_filename(
        &self,
        filename: &std::path::Path,
    ) -> Result<std::rc::Rc<dyn Exporter>, ExportError> {
        self.exporters.exporter_by_filename(filename)
    }
}