rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting 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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//! Resolve callable identities for compiler lowering after type checking.
use super::*;

pub(crate) fn resolve_program_calls(
    program: &Program,
    source: SourceId,
    definitions: &DefMap,
    host_functions: &HashMap<String, FunctionSignature>,
    results: &mut TypeckResults,
    declarations: (&DeclarationTypeResolver, &[String]),
    host: (
        &crate::HostTypeResolutionResults,
        Option<&rils_host::HostContract>,
    ),
) -> Vec<crate::analysis::AnalysisDiagnostic> {
    resolve_project_calls(
        &[(source, declarations.1, program)],
        definitions,
        host_functions,
        results,
        host,
        declarations.0,
    )
}

pub(crate) fn resolve_project_calls(
    units: &[(SourceId, &[String], &Program)],
    definitions: &DefMap,
    host_functions: &HashMap<String, FunctionSignature>,
    results: &mut TypeckResults,
    host: (
        &crate::HostTypeResolutionResults,
        Option<&rils_host::HostContract>,
    ),
    declarations: &DeclarationTypeResolver,
) -> Vec<crate::analysis::AnalysisDiagnostic> {
    let mut diagnostics = Vec::new();
    results.executable_patterns.clear();
    // A project rebinds every occurrence using all modules' declarations,
    // including fields that were absent or shadowed in a document-only view.
    results.resolved_fields.clear();
    let mut callables = CallableDefinitions {
        declarations: declarations.clone(),
        ..Default::default()
    };
    for (_, module_path, program) in units {
        collect_callable_definitions(
            &program.statements,
            &mut module_path.to_vec(),
            definitions,
            &mut callables,
        );
    }
    for (_, module_path, program) in units {
        collect_callable_aliases(
            &program.statements,
            &mut module_path.to_vec(),
            &mut callables,
        );
        collect_host_aliases(
            &program.statements,
            &mut module_path.to_vec(),
            host_functions,
            &mut callables.host_aliases,
        );
    }
    for (source, module_path, program) in units {
        let expression_ids = ExpressionIdentityMap::allocate(program, *source);
        let host_types = crate::HostTypeResolutionView::new(program, *source, host.0);
        visit_statements(
            &program.statements,
            &mut module_path.to_vec(),
            None,
            &mut |expression, namespace, self_type| {
                let id = expression_ids
                    .get(expression)
                    .expect("visited expression must have a semantic identity");
                if let Expr::Match { arms, .. } = expression {
                    for arm in arms {
                        let pattern = results.arm_pattern(&expression_ids, arm);
                        match patterns::resolve(declarations, namespace, self_type, host.1, pattern)
                        {
                            Ok(plan) => {
                                results
                                    .executable_patterns
                                    .insert(expression_ids.id(&arm.expression), plan.into());
                            }
                            Err(error) => diagnostics.push(error),
                        }
                    }
                }
                if let Expr::Member { object, name, .. } = expression
                    && let Some(ty) = results.expression_type(expression_ids.id(object))
                    && let Some(field) = declarations.resolved_record_field(ty, name)
                {
                    results.resolved_fields.insert(id, field);
                }
                if let Some(definition) = lexical_callee_definition(expression, definitions)
                    .or_else(|| {
                        callables.resolve(
                            expression,
                            &expression_ids,
                            results,
                            namespace,
                            self_type,
                        )
                    })
                {
                    results.resolve_value(id, definition);
                }
                let context = CallResolutionContext {
                    definitions,
                    callables: &callables,
                    host_functions,
                    expression_ids: &expression_ids,
                    results,
                    namespace,
                    self_type,
                    host_types: &host_types,
                };
                let Expr::Call {
                    callee, arguments, ..
                } = expression
                else {
                    // Imported function values use the same canonical path
                    // resolution as direct calls, including imports and shadowing.
                    if matches!(
                        expression,
                        Expr::Variable { .. } | Expr::Path { .. } | Expr::GenericPath { .. }
                    ) && let Some(call) = resolve_callee(expression, &[], &context)
                    {
                        let call = match call {
                            ResolvedCall::Import { ref name, .. } => {
                                if let Some(symbol) = rils_builtins::builtin_function(name)
                                    .and_then(|declaration| declaration.native_symbol)
                                {
                                    ResolvedCall::Native {
                                        symbol,
                                        receiver: None,
                                    }
                                } else {
                                    call
                                }
                            }
                            ResolvedCall::Host { .. } => call,
                            _ => return,
                        };
                        results.resolve_call(id, call);
                    }
                    return;
                };
                if !matches!(
                    results.resolved_call(id),
                    Some(ResolvedCall::SumConstructor { .. })
                ) && let Some(call) = resolve_callee(callee, arguments, &context)
                {
                    results.resolve_call(id, call);
                }
            },
        );
    }
    diagnostics
}

struct CallResolutionContext<'a> {
    definitions: &'a DefMap,
    callables: &'a CallableDefinitions,
    host_functions: &'a HashMap<String, FunctionSignature>,
    expression_ids: &'a ExpressionIdentityMap,
    results: &'a TypeckResults,
    namespace: &'a [String],
    self_type: Option<&'a str>,
    host_types: &'a crate::HostTypeResolutionView<'a>,
}

fn resolve_callee(
    callee: &Expr,
    arguments: &[Expr],
    context: &CallResolutionContext<'_>,
) -> Option<ResolvedCall> {
    let CallResolutionContext {
        definitions,
        callables,
        host_functions,
        expression_ids,
        results,
        namespace,
        self_type,
        host_types,
    } = context;
    if let Some(definition) = lexical_callee_definition(callee, definitions) {
        return Some(ResolvedCall::Definition(definition));
    }
    if let Some(identity) = function_references::callee_span(callee)
        .and_then(|span| definitions.external_function(span))
    {
        return match identity {
            crate::analysis::ExternalFunction::Builtin(path) => standard_import(path),
            crate::analysis::ExternalFunction::Host(path) => {
                Some(ResolvedCall::Host { path: path.clone() })
            }
        };
    }
    if let Some(definition) = callables
        .resolve(callee, expression_ids, results, namespace, *self_type)
        .or_else(|| callables.resolve_member_call(callee, arguments, expression_ids, results))
    {
        return Some(ResolvedCall::Definition(definition));
    }
    if let Expr::Path { segments, .. } = callee
        && let [.., _, member] = segments.as_slice()
        && let Some(receiver) = arguments.first()
        && let Some(receiver_type) = expression_ids
            .get(receiver)
            .and_then(|id| results.expression_type(id))
    {
        let resolved_trait = callables.declarations.resolve(
            &Type::named(segments[..segments.len() - 1].join("::")),
            namespace,
        );
        if let Some(call) = builtin_source_impl_call(
            receiver_type,
            Some(&resolved_trait),
            member,
            &callables.declarations,
        ) {
            return Some(call);
        }
        let receiver_type = match (
            callables
                .declarations
                .trait_receiver_mode(&resolved_trait, member),
            receiver_type,
        ) {
            (
                Some(rils_builtins::ReceiverMode::Shared | rils_builtins::ReceiverMode::Mutable),
                Type::Reference { inner, .. },
            ) => inner.as_ref(),
            _ => receiver_type,
        };
        if let Some(definition) = callables.trait_method(receiver_type, &resolved_trait, member) {
            return Some(ResolvedCall::Definition(definition));
        }
        if let Type::Named { name, .. } = &resolved_trait
            && let Some(default) =
                builtin_source_default_call(name, receiver_type, member, &callables.declarations)
        {
            return Some(default);
        }
    }
    if let Expr::Member { object, .. } = callee
        && expression_ids
            .get(object)
            .and_then(|id| results.expression_type(id))
            .is_none_or(|ty| matches!(ty, Type::Unknown))
        && let Some(definition) = callables.resolve_untyped_member(callee)
    {
        return Some(ResolvedCall::Definition(definition));
    }
    if let Some(path) = callables.resolve_host(callee, host_functions, namespace, *self_type) {
        return Some(ResolvedCall::Host { path });
    }
    if let Some(definition) = callee_definition(callee, definitions) {
        if let Some(data) = definitions.definition(definition)
            && data.kind == SymbolKind::Function
            && let Some(import) =
                standard_import(&callables.resolve_path(namespace, *self_type, &data.name))
        {
            return Some(import);
        }
        return Some(ResolvedCall::Definition(definition));
    }
    if let Expr::QualifiedPath {
        target,
        trait_name,
        trait_arguments,
        member,
        ..
    } = callee
    {
        let required = callables.declarations.resolve(
            &Type::Named {
                name: trait_name.clone(),
                arguments: trait_arguments.clone(),
            },
            namespace,
        );
        let target = callables.declarations.resolve(target, namespace);
        if let Some(call) =
            builtin_source_impl_call(&target, Some(&required), member, &callables.declarations)
        {
            return Some(call);
        }
        if let Type::Named { name, .. } = required
            && let Some(default) =
                builtin_source_default_call(&name, &target, member, &callables.declarations)
        {
            return Some(default);
        }
    }
    match callee {
        Expr::Member { object, name, .. } => {
            let receiver = results.expression_type(expression_ids.get(object)?)?;
            if let Some(call) =
                builtin_source_impl_call(receiver, None, name, &callables.declarations)
            {
                return Some(call);
            }
            let mut receiver = receiver;
            while let Type::Reference { inner, .. } = receiver {
                receiver = inner;
            }
            let intrinsic = match receiver {
                Type::Integer(_) | Type::IntegerVariable(_) => crate::integer_method(name),
                Type::Float(_) | Type::FloatVariable(_) => crate::float_method(name),
                _ => None,
            };
            if let Some(intrinsic) = intrinsic {
                return Some(ResolvedCall::NumericIntrinsic {
                    symbol: intrinsic.symbol,
                    receiver: Some(rils_builtins::ReceiverMode::Owned),
                });
            }
            let member =
                crate::standard_library::builtin_member_for_type(receiver, name).or_else(|| {
                    (name == "clone")
                        .then(|| rils_builtins::builtin_member("Clone", "clone"))
                        .flatten()
                });
            if let Some(member) =
                member.filter(|member| member.kind == rils_builtins::BuiltinMemberKind::Method)
            {
                if let Some(symbol) = member.native_symbol {
                    return Some(ResolvedCall::Native {
                        symbol,
                        receiver: member.receiver,
                    });
                }
                return None;
            }
            let candidates = crate::standard_library::native_trait_method_candidates(
                name,
                |owner| {
                    receiver.is_concrete_type()
                        && !matches!(receiver, Type::Named { name, .. } if callables.declarations.is_declared_type(name))
                        && callables.declarations.implements_trait(receiver, owner)
                },
            );
            let defaults =
                crate::standard_library::builtin_trait_default_candidates(name, |owner| {
                    callables.declarations.implements_trait(receiver, owner)
                });
            if let ([(_, member)], []) = (candidates.as_slice(), defaults.as_slice()) {
                return Some(ResolvedCall::Native {
                    symbol: member.native_symbol?,
                    receiver: member.receiver,
                });
            }
            if let ([], [(trait_name, member)]) = (candidates.as_slice(), defaults.as_slice()) {
                return Some(ResolvedCall::TraitDefault {
                    trait_name,
                    method: member.name,
                    receiver: member.receiver?,
                });
            }
            let Type::Named { name: owner, .. } = receiver else {
                return None;
            };
            let path = format!("{owner}::{name}");
            host_functions
                .contains_key(&path)
                .then_some(ResolvedCall::Host { path })
        }
        Expr::Path { segments, .. } | Expr::GenericPath { segments, .. } => {
            let segments = host_types
                .resolved_expression_path(callee)
                .unwrap_or(segments);
            let path = segments.join("::");
            if let Some((member, owner)) =
                segments.split_last().filter(|(_, owner)| !owner.is_empty())
            {
                let arguments = match callee {
                    Expr::GenericPath { arguments, .. } => arguments.clone(),
                    _ => Vec::new(),
                };
                let owner = callables.declarations.associated_owner(
                    &Type::Named {
                        name: owner.join("::"),
                        arguments,
                    },
                    namespace,
                );
                if !matches!(&owner, Type::Named { name, .. } if callables.declarations.is_declared_type(name))
                    && let Some(import) = builtin_associated_import(&owner, member)
                {
                    return Some(import);
                }
            }
            standard_import(&path).or_else(|| {
                host_functions
                    .contains_key(&path)
                    .then_some(ResolvedCall::Host { path })
            })
        }
        Expr::Variable { name, .. } => native_macro_import(name)
            .or_else(|| standard_import(&callables.resolve_path(namespace, *self_type, name)))
            .or_else(|| standard_import(name))
            .or_else(|| {
                host_functions
                    .contains_key(name)
                    .then(|| ResolvedCall::Host { path: name.clone() })
            }),
        _ => None,
    }
}

fn builtin_source_impl_call(
    target: &Type,
    required: Option<&Type>,
    method: &str,
    declarations: &DeclarationTypeResolver,
) -> Option<ResolvedCall> {
    let (id, receiver) = declarations.builtin_impl_method(target, required, method)?;
    Some(ResolvedCall::BuiltinImpl {
        implementation: id.into(),
        method: method.into(),
        receiver,
        target: target.clone(),
    })
}

fn builtin_source_default_call(
    trait_name: &str,
    receiver: &Type,
    method: &str,
    declarations: &DeclarationTypeResolver,
) -> Option<ResolvedCall> {
    let trait_name = crate::standard_library::builtin_trait_name(trait_name)?;
    let member = rils_builtins::builtin_member(trait_name, method)?;
    if member.native_symbol.is_some()
        || !declarations.implements_trait(receiver, trait_name)
        || crate::builtin_trait_default(trait_name, method).is_none()
        || crate::standard_library::builtin_trait_member_for_type(receiver, trait_name, method)
            .is_some()
    {
        return None;
    }
    Some(ResolvedCall::TraitDefault {
        trait_name,
        method: member.name,
        receiver: member.receiver?,
    })
}

fn builtin_associated_import(owner: &Type, member_name: &str) -> Option<ResolvedCall> {
    let member =
        crate::standard_library::builtin_member_for_type(owner, member_name).or_else(|| {
            let Type::Named { name, .. } = owner else {
                return None;
            };
            rils_builtins::builtin_member(
                crate::standard_library::builtin_trait_name(name)?,
                member_name,
            )
        })?;
    if member.kind == rils_builtins::BuiltinMemberKind::Constant {
        return None;
    }
    Some(ResolvedCall::Native {
        symbol: member.native_symbol?,
        // A type-qualified method receives its receiver as an explicit argument.
        receiver: None,
    })
}

fn standard_import(path: &str) -> Option<ResolvedCall> {
    let declaration = rils_builtins::builtin_function(path)?;
    let signature = crate::standard_library::standard_function_signature(path)?;
    let capability = match declaration.backend {
        rils_builtins::BuiltinBackend::Host(capability) => capability,
        rils_builtins::BuiltinBackend::Runtime => "core",
        rils_builtins::BuiltinBackend::Intrinsic | rils_builtins::BuiltinBackend::Metadata => {
            return None;
        }
    };
    Some(ResolvedCall::Import {
        name: path.into(),
        signature,
        capability: capability.into(),
    })
}

fn native_macro_import(name: &str) -> Option<ResolvedCall> {
    standard_import(rils_builtins::macro_function(name)?.path)
}

fn collect_callable_definitions(
    statements: &[Stmt],
    namespace: &mut Vec<String>,
    definitions: &DefMap,
    output: &mut CallableDefinitions,
) {
    for statement in statements {
        match statement {
            Stmt::Module {
                name,
                statements: Some(statements),
                ..
            } => {
                namespace.push(name.clone());
                collect_callable_definitions(statements, namespace, definitions, output);
                namespace.pop();
            }
            Stmt::Function {
                name, name_span, ..
            } => {
                if let Some(definition) = definitions.resolution(*name_span) {
                    output
                        .functions
                        .insert(qualified_name(namespace, name), definition);
                }
            }
            Stmt::Impl {
                target,
                trait_name,
                trait_arguments,
                methods,
                span,
                ..
            } => {
                let owner = match output.declarations.resolve(target, namespace) {
                    Type::Named { name, .. } => name,
                    other => other.to_string(),
                };
                let required = trait_name.as_ref().map(|trait_name| {
                    match output.declarations.resolve(
                        &Type::Named {
                            name: trait_name.clone(),
                            arguments: trait_arguments.clone(),
                        },
                        namespace,
                    ) {
                        required @ Type::Named { .. } => output
                            .declarations
                            .trait_instance(target, &required)
                            .unwrap_or(required),
                        _ => Type::named(qualified_name(namespace, trait_name)),
                    }
                });
                output.methods.extend(methods.iter().filter_map(|method| {
                    Some(MethodDefinition {
                        source: SourceMethodId::new(
                            *span,
                            trait_name.as_deref().unwrap_or_default(),
                            &method.name,
                        ),
                        owner: owner.clone(),
                        trait_name: required.as_ref().and_then(|ty| match ty {
                            Type::Named { name, .. } => Some(name.clone()),
                            _ => None,
                        }),
                        name: method.name.clone(),
                        definition: definitions.resolution(method.name_span)?,
                    })
                }));
            }
            _ => {}
        }
    }
}

fn collect_host_aliases(
    statements: &[Stmt],
    namespace: &mut Vec<String>,
    host_functions: &HashMap<String, FunctionSignature>,
    output: &mut HashMap<String, String>,
) {
    for statement in statements {
        match statement {
            Stmt::Module {
                name,
                statements: Some(statements),
                ..
            } => {
                namespace.push(name.clone());
                collect_host_aliases(statements, namespace, host_functions, output);
                namespace.pop();
            }
            Stmt::Use { imports, .. } => {
                for import in imports {
                    let path = import.path.join("::");
                    if import.kind == crate::ast::UseImportKind::Glob {
                        let prefix = format!("{path}::");
                        for candidate in host_functions.keys() {
                            let Some(member) = candidate.strip_prefix(&prefix) else {
                                continue;
                            };
                            if !member.contains("::") {
                                output.insert(qualified_name(namespace, member), candidate.clone());
                            }
                        }
                    } else if host_functions.contains_key(&path)
                        && let Some(binding) = import.binding_name()
                    {
                        output.insert(qualified_name(namespace, binding), path);
                    }
                }
            }
            _ => {}
        }
    }
}

fn collect_callable_aliases(
    statements: &[Stmt],
    namespace: &mut Vec<String>,
    callables: &mut CallableDefinitions,
) {
    for statement in statements {
        match statement {
            Stmt::Module {
                name,
                statements: Some(statements),
                ..
            } => {
                namespace.push(name.clone());
                collect_callable_aliases(statements, namespace, callables);
                namespace.pop();
            }
            Stmt::Use { imports, .. } => {
                for import in imports {
                    let path = contextual_name(namespace, None, &import.path.join("::"));
                    if import.kind == crate::ast::UseImportKind::Glob {
                        let prefix = format!("{path}::");
                        let aliases = callables
                            .functions
                            .iter()
                            .filter_map(|(candidate, definition)| {
                                let member = candidate.strip_prefix(&prefix)?;
                                (!member.contains("::")).then_some((member.to_owned(), *definition))
                            })
                            .collect::<Vec<_>>();
                        for (member, definition) in aliases {
                            callables
                                .functions
                                .insert(qualified_name(namespace, &member), definition);
                        }
                        let modules = callables
                            .functions
                            .keys()
                            .filter_map(|candidate| {
                                let remaining = candidate.strip_prefix(&prefix)?;
                                remaining
                                    .split_once("::")
                                    .map(|(module, _)| module.to_owned())
                            })
                            .collect::<HashSet<_>>();
                        for module in modules {
                            callables.path_aliases.insert(
                                qualified_name(namespace, &module),
                                format!("{path}::{module}"),
                            );
                        }
                    } else if let Some(binding) = import.binding_name() {
                        let binding = qualified_name(namespace, binding);
                        if let Some(definition) = callables.functions.get(&path).copied() {
                            callables.functions.insert(binding, definition);
                        } else if rils_builtins::builtin_function(&path).is_some()
                            || callables
                                .functions
                                .keys()
                                .any(|candidate| candidate.starts_with(&format!("{path}::")))
                        {
                            callables.path_aliases.insert(binding, path);
                        }
                    }
                }
            }
            _ => {}
        }
    }
}