lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
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
use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt;

use crate::parsing::Span;
use crate::semantic::{
    CollectedAliasArgument, CollectedExtension, CollectedSymbolKind, ModuleGraph, ModuleGraphError,
    ResolvedSymbol,
};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct CanonicalSymbolPath {
    pub module: String,
    pub local: String,
}

impl CanonicalSymbolPath {
    pub(crate) fn from_resolved(symbol: &ResolvedSymbol<'_>) -> Self {
        Self {
            module: symbol.module_path.to_owned(),
            local: symbol.local_path.to_owned(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveExtensionFunction {
    pub relative_path: String,
    pub declaration: CanonicalSymbolPath,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveTraitImplementation {
    pub trait_path: String,
    pub span: Span,
    pub associated_types: BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveExtension {
    pub origin_module: String,
    pub symbol: Option<String>,
    pub target: CanonicalSymbolPath,
    pub generic_parameters: Vec<String>,
    pub target_arguments: Vec<CollectedAliasArgument>,
    pub functions: Vec<ActiveExtensionFunction>,
    pub trait_implementations: Vec<ActiveTraitImplementation>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ExtensionEnvironment {
    pub extensions: Vec<ActiveExtension>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExtensionActivationError {
    Resolution(ModuleGraphError),
    MissingImportedModule {
        requested_by: String,
        path: String,
    },
    MissingExtensionMetadata {
        module: String,
        symbol: String,
    },
    FunctionConflict {
        target: CanonicalSymbolPath,
        relative_path: String,
        first_extension: String,
        second_extension: String,
    },
    TraitImplementationConflict {
        target: CanonicalSymbolPath,
        trait_path: String,
        first_extension: String,
        second_extension: String,
    },
}

impl fmt::Display for ExtensionActivationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Resolution(error) => error.fmt(formatter),
            Self::MissingImportedModule { requested_by, path } => {
                write!(
                    formatter,
                    "module `{requested_by}` imports missing module `{path}`"
                )
            }
            Self::MissingExtensionMetadata { module, symbol } => {
                write!(
                    formatter,
                    "missing metadata for extension `{module}::{symbol}`"
                )
            }
            Self::FunctionConflict {
                target,
                relative_path,
                ..
            } => write!(
                formatter,
                "multiple visible extensions define `{relative_path}` for `{}::{}`",
                target.module, target.local
            ),
            Self::TraitImplementationConflict {
                target, trait_path, ..
            } => write!(
                formatter,
                "multiple visible extensions implement `{trait_path}` for `{}::{}`",
                target.module, target.local
            ),
        }
    }
}

impl Error for ExtensionActivationError {}

impl From<ModuleGraphError> for ExtensionActivationError {
    fn from(value: ModuleGraphError) -> Self {
        Self::Resolution(value)
    }
}

impl ExtensionEnvironment {
    pub fn build(
        graph: &ModuleGraph,
        requesting_module: &str,
    ) -> Result<Self, Vec<ExtensionActivationError>> {
        let Some(module) = graph.module(requesting_module) else {
            return Err(vec![ExtensionActivationError::Resolution(
                ModuleGraphError::UnknownModule {
                    path: requesting_module.to_owned(),
                },
            )]);
        };

        let mut candidates = BTreeSet::<(String, Option<String>)>::new();
        for extension in &module.declarations.extensions {
            candidates.insert((module.path.clone(), extension.symbol.clone()));
        }

        for symbol in module.declarations.symbols.values() {
            match &symbol.kind {
                CollectedSymbolKind::ModuleAlias { source } => {
                    let Some(imported) = graph.module(source) else {
                        continue;
                    };
                    for extension in &imported.declarations.extensions {
                        if extension.symbol.is_none() {
                            candidates.insert((imported.path.clone(), None));
                        }
                    }
                }
                CollectedSymbolKind::Alias { .. } => {
                    if let Ok(resolved) = graph.resolve(requesting_module, &symbol.path)
                        && matches!(resolved.symbol.kind, CollectedSymbolKind::Extension { .. })
                    {
                        candidates.insert((
                            resolved.module_path.to_owned(),
                            Some(resolved.local_path.to_owned()),
                        ));
                    }
                }
                _ => {}
            }
        }

        // Prelude may activate both file-wide extensions and explicitly aliased
        // named extensions. This is how core opts primitive types into traits
        // without making implementations globally inherent.
        if let Some(prelude_path) = graph.prelude()
            && let Some(prelude) = graph.module(prelude_path)
        {
            for extension in &prelude.declarations.extensions {
                if extension.symbol.is_none() {
                    candidates.insert((prelude.path.clone(), None));
                }
            }
            for symbol in prelude.declarations.symbols.values() {
                if let CollectedSymbolKind::Alias { .. } = &symbol.kind
                    && let Ok(resolved) = graph.resolve(prelude_path, &symbol.path)
                    && matches!(resolved.symbol.kind, CollectedSymbolKind::Extension { .. })
                {
                    candidates.insert((
                        resolved.module_path.to_owned(),
                        Some(resolved.local_path.to_owned()),
                    ));
                }
            }
        }

        let mut errors = Vec::new();
        let mut extensions = Vec::new();
        for (origin, symbol) in candidates {
            match activate(graph, &origin, symbol.as_deref()) {
                Ok(extension) => extensions.push(extension),
                Err(error) => errors.push(error),
            }
        }

        detect_conflicts(&extensions, &mut errors);
        if errors.is_empty() {
            Ok(Self { extensions })
        } else {
            Err(errors)
        }
    }
}

fn activate(
    graph: &ModuleGraph,
    origin_module: &str,
    symbol: Option<&str>,
) -> Result<ActiveExtension, ExtensionActivationError> {
    let module = graph.module(origin_module).ok_or_else(|| {
        ExtensionActivationError::MissingImportedModule {
            requested_by: origin_module.to_owned(),
            path: origin_module.to_owned(),
        }
    })?;
    let metadata = find_extension(&module.declarations.extensions, symbol).ok_or_else(|| {
        ExtensionActivationError::MissingExtensionMetadata {
            module: origin_module.to_owned(),
            symbol: symbol.unwrap_or("<file>").to_owned(),
        }
    })?;
    let target =
        CanonicalSymbolPath::from_resolved(&graph.resolve(origin_module, &metadata.target)?);

    let prefix = metadata.symbol.as_deref();
    let mut functions = Vec::new();
    for declaration in module.declarations.symbols.values() {
        let CollectedSymbolKind::Declaration(ids) = &declaration.kind else {
            continue;
        };
        if ids.function.is_none() {
            continue;
        }
        let Some(relative_path) = relative_to_extension(&declaration.path, prefix) else {
            continue;
        };
        functions.push(ActiveExtensionFunction {
            relative_path,
            declaration: CanonicalSymbolPath {
                module: origin_module.to_owned(),
                local: declaration.path.clone(),
            },
        });
    }

    let mut trait_implementations = Vec::new();
    for implementation in &module.declarations.trait_implementations {
        if !belongs_to_extension(&implementation.owner, prefix) {
            continue;
        }
        let implementation_path = if implementation.owner.is_empty() {
            implementation.trait_path.clone()
        } else {
            format!("{}.{}", implementation.owner, implementation.trait_path)
        };
        let associated_prefix = format!("{implementation_path}.");
        let associated_types = module
            .declarations
            .symbols
            .values()
            .filter_map(|symbol| {
                let CollectedSymbolKind::AssociatedType {
                    binding: Some(binding),
                } = &symbol.kind
                else {
                    return None;
                };
                let name = symbol.path.strip_prefix(&associated_prefix)?;
                (!name.contains('.')).then_some((name.to_owned(), binding.clone()))
            })
            .collect();
        trait_implementations.push(ActiveTraitImplementation {
            trait_path: implementation.trait_path.clone(),
            span: implementation.span,
            associated_types,
        });
    }

    Ok(ActiveExtension {
        origin_module: origin_module.to_owned(),
        symbol: metadata.symbol.clone(),
        target,
        generic_parameters: metadata
            .parameters
            .iter()
            .map(|parameter| parameter.name.clone())
            .collect(),
        target_arguments: metadata.target_arguments.clone(),
        functions,
        trait_implementations,
    })
}

fn find_extension<'a>(
    extensions: &'a [CollectedExtension],
    symbol: Option<&str>,
) -> Option<&'a CollectedExtension> {
    extensions
        .iter()
        .find(|extension| extension.symbol.as_deref() == symbol)
}

fn belongs_to_extension(path: &str, prefix: Option<&str>) -> bool {
    match prefix {
        None => true,
        Some(prefix) => path == prefix || path.starts_with(&format!("{prefix}.")),
    }
}

fn relative_to_extension(path: &str, prefix: Option<&str>) -> Option<String> {
    match prefix {
        None => Some(path.to_owned()),
        Some(prefix) => path
            .strip_prefix(prefix)
            .and_then(|path| path.strip_prefix('.'))
            .map(str::to_owned),
    }
}

fn extension_name(extension: &ActiveExtension) -> String {
    match &extension.symbol {
        Some(symbol) => format!("{}::{symbol}", extension.origin_module),
        None => extension.origin_module.clone(),
    }
}

fn detect_conflicts(extensions: &[ActiveExtension], errors: &mut Vec<ExtensionActivationError>) {
    let mut functions = BTreeMap::<(CanonicalSymbolPath, String), String>::new();
    let mut traits = BTreeMap::<(CanonicalSymbolPath, String), String>::new();
    for extension in extensions {
        let name = extension_name(extension);
        for function in &extension.functions {
            let key = (extension.target.clone(), function.relative_path.clone());
            if let Some(first) = functions.insert(key, name.clone()) {
                errors.push(ExtensionActivationError::FunctionConflict {
                    target: extension.target.clone(),
                    relative_path: function.relative_path.clone(),
                    first_extension: first,
                    second_extension: name.clone(),
                });
            }
        }
        for implementation in &extension.trait_implementations {
            let key = (extension.target.clone(), implementation.trait_path.clone());
            if let Some(first) = traits.insert(key, name.clone()) {
                errors.push(ExtensionActivationError::TraitImplementationConflict {
                    target: extension.target.clone(),
                    trait_path: implementation.trait_path.clone(),
                    first_extension: first,
                    second_extension: name.clone(),
                });
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parsing::{SourceFile, parse_file};
    use crate::semantic::DeclarationIndex;

    fn insert(graph: &mut ModuleGraph, path: &str, source: &str) {
        let parsed = parse_file(SourceFile { path, text: source }).unwrap();
        graph
            .insert(path, DeclarationIndex::collect(&parsed).unwrap())
            .unwrap();
    }

    fn base_graph() -> ModuleGraph {
        let mut graph = ModuleGraph::default();
        insert(&mut graph, "lib://types.lt", "pub acs Target: struct");
        insert(
            &mut graph,
            "lib://extension.lt",
            "acs types: \"lib://types.lt\" as extension for types.Target acs extra: fn()",
        );
        graph
    }

    #[test]
    fn file_extension_is_active_only_when_its_module_is_imported() {
        let mut graph = base_graph();
        insert(&mut graph, "app://without.lt", "");
        insert(
            &mut graph,
            "app://with.lt",
            "acs ext_module: \"lib://extension.lt\"",
        );

        assert!(
            ExtensionEnvironment::build(&graph, "app://without.lt")
                .unwrap()
                .extensions
                .is_empty()
        );
        let environment = ExtensionEnvironment::build(&graph, "app://with.lt").unwrap();
        assert_eq!(environment.extensions.len(), 1);
        assert_eq!(environment.extensions[0].target.module, "lib://types.lt");
        assert_eq!(environment.extensions[0].target.local, "Target");
        assert_eq!(
            environment.extensions[0].functions[0].relative_path,
            "extra"
        );
    }

    #[test]
    fn named_extension_requires_an_explicit_symbol_import() {
        let mut graph = ModuleGraph::default();
        insert(&mut graph, "lib://types.lt", "pub acs Target: struct");
        insert(
            &mut graph,
            "lib://named.lt",
            "acs types: \"lib://types.lt\" pub acs named: extension for types.Target { acs extra: fn() }",
        );
        insert(
            &mut graph,
            "app://module-only.lt",
            "acs extensions: \"lib://named.lt\"",
        );
        insert(
            &mut graph,
            "app://selected.lt",
            "acs extensions: \"lib://named.lt\" acs selected: extensions.named",
        );

        assert!(
            ExtensionEnvironment::build(&graph, "app://module-only.lt")
                .unwrap()
                .extensions
                .is_empty()
        );
        let selected = ExtensionEnvironment::build(&graph, "app://selected.lt").unwrap();
        assert_eq!(selected.extensions.len(), 1);
        assert_eq!(selected.extensions[0].symbol.as_deref(), Some("named"));
    }

    #[test]
    fn reports_conflicting_visible_extension_functions() {
        let mut graph = base_graph();
        insert(
            &mut graph,
            "lib://other-extension.lt",
            "acs types: \"lib://types.lt\" as extension for types.Target acs extra: fn()",
        );
        insert(
            &mut graph,
            "app://main.lt",
            "acs first: \"lib://extension.lt\" acs second: \"lib://other-extension.lt\"",
        );

        let errors = ExtensionEnvironment::build(&graph, "app://main.lt").unwrap_err();
        assert!(errors.iter().any(|error| matches!(
            error,
            ExtensionActivationError::FunctionConflict { relative_path, .. }
                if relative_path == "extra"
        )));
    }
}