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
use std::collections::{HashMap, HashSet};

use crate::{
    BodyId, DefId, ExprId, ImplId, SourceId, Span, Type,
    analysis::SymbolOccurrence,
    ast::{Expr, Program, Stmt},
    types::FunctionSignature,
};

mod callable_lookup;
mod capabilities;
pub use capabilities::{
    CallableCapabilities, CallableKind, callable_contract_signature, infer_callable_generics,
};
mod calls;
mod patterns;
pub(crate) use calls::{resolve_program_calls, resolve_project_calls};
pub use patterns::{MatchPattern, ResolvedPattern, VariantId};
mod declaration_types;
use callable_lookup::*;
pub(crate) use declaration_types::associated_signature_bindings;
mod documents;
mod expression_ids;
mod function_references;
pub(crate) use function_references::FunctionReferences;
pub(crate) use function_references::callee_span;
use function_references::{callee_definition, lexical_callee_definition};
mod syntax_ids;
mod visit;

pub use declaration_types::{
    DeclarationTypeResolver, SourceMethodId, TraitObligation, requires_storage_declaration,
    source_type_path,
};
pub use expression_ids::ExpressionIdentityMap;
pub(crate) use expression_ids::{ExpressionIds, ExpressionTypes};
pub use syntax_ids::{PatternIdentityMap, TypeIdentityMap};
use visit::visit_statements;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SymbolKind {
    Variable,
    Parameter,
    Function,
    Macro,
    Type,
    Trait,
    Method,
    Field,
    Variant,
    Module,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SymbolContainer {
    Module(String),
    Type(String),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DefinitionData {
    pub id: DefId,
    pub name: String,
    pub span: Span,
    pub kind: SymbolKind,
    pub container: Option<SymbolContainer>,
    pub inferred_type: Option<Type>,
    pub detail: Option<String>,
}

/// Definitions and resolved source occurrences for one analyzed program.
///
/// Consumers use this table to move from syntax locations to semantic
/// identities and back without repeating textual name lookup.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DefMap {
    definitions: HashMap<DefId, DefinitionData>,
    resolutions: HashMap<Span, DefId>,
    external_functions: HashMap<Span, crate::analysis::ExternalFunction>,
    bodies: HashMap<Span, BodyId>,
    definition_bodies: HashMap<DefId, BodyId>,
    impls: HashMap<Span, ImplId>,
}

impl DefMap {
    pub(crate) fn from_symbols_and_owners(
        symbols: &[SymbolOccurrence],
        owners: SemanticOwnerIds,
    ) -> Self {
        let mut result = Self::default();
        for symbol in SymbolOccurrence::source_last(symbols) {
            if let Some(identity) = &symbol.external_function {
                result
                    .external_functions
                    .insert(symbol.span, identity.clone());
            }
            let id = if symbol.is_definition {
                let Some(id) = symbol.symbol_id else {
                    continue;
                };
                result.definitions.insert(
                    id,
                    DefinitionData {
                        id,
                        name: symbol.name.clone(),
                        span: symbol.span,
                        kind: symbol.kind,
                        container: symbol.container.clone(),
                        inferred_type: symbol.inferred_type.clone(),
                        detail: symbol.detail.clone(),
                    },
                );
                id
            } else {
                let Some(id) = symbol.definition_id else {
                    continue;
                };
                id
            };
            result
                .resolutions
                .insert(symbol.span, symbol.definition_id.unwrap_or(id));
        }
        for (definition, body_span) in owners.bodies {
            let body = BodyId(definition);
            result.bodies.insert(body_span, body);
            result.definition_bodies.insert(definition, body);
        }
        for (span, id) in owners.impls {
            result.impls.insert(span, id);
        }
        result
    }

    pub fn definition(&self, id: DefId) -> Option<&DefinitionData> {
        self.definitions.get(&id)
    }

    pub fn resolution(&self, span: Span) -> Option<DefId> {
        self.resolutions.get(&span).copied()
    }

    pub fn external_function(&self, span: Span) -> Option<&crate::analysis::ExternalFunction> {
        self.external_functions.get(&span)
    }

    pub fn definition_at(&self, span: Span) -> Option<&DefinitionData> {
        self.resolution(span).and_then(|id| self.definition(id))
    }

    pub fn definitions(&self) -> impl Iterator<Item = &DefinitionData> {
        self.definitions.values()
    }

    pub fn body(&self, definition: DefId) -> Option<BodyId> {
        self.definition_bodies.get(&definition).copied()
    }

    pub fn body_at(&self, span: Span) -> Option<BodyId> {
        self.bodies.get(&span).copied()
    }

    pub fn impl_at(&self, span: Span) -> Option<ImplId> {
        self.impls.get(&span).copied()
    }

    pub fn impls(&self) -> impl Iterator<Item = (Span, ImplId)> + '_ {
        self.impls.iter().map(|(span, id)| (*span, *id))
    }

    pub(crate) fn extend(&mut self, other: Self) {
        self.definitions.extend(other.definitions);
        self.resolutions.extend(other.resolutions);
        self.external_functions.extend(other.external_functions);
        self.bodies.extend(other.bodies);
        self.definition_bodies.extend(other.definition_bodies);
        self.impls.extend(other.impls);
    }
}

#[derive(Default)]
pub(crate) struct SemanticOwnerIds {
    bodies: Vec<(DefId, Span)>,
    impls: Vec<(Span, ImplId)>,
    next_impl_by_source: HashMap<SourceId, u32>,
}

impl SemanticOwnerIds {
    pub(crate) fn record_body(&mut self, definition: DefId, span: Span) {
        self.bodies.push((definition, span));
    }

    pub(crate) fn allocate_impl(&mut self, span: Span, fallback_source: SourceId) -> ImplId {
        let source = if span.source == SourceId::UNKNOWN {
            fallback_source
        } else {
            span.source
        };
        let next = self.next_impl_by_source.entry(source).or_insert(0);
        assert!(
            *next < crate::database::identities::PERSISTENT_ID_BIT,
            "impl id overflow"
        );
        let id = ImplId {
            source,
            local: *next,
        };
        *next = next.checked_add(1).expect("impl id overflow");
        self.impls.push((span, id));
        id
    }

    pub(crate) fn record_impl(&mut self, span: Span, id: ImplId) {
        self.impls.push((span, id));
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResolvedCall {
    Definition(DefId),
    SumConstructor {
        name: &'static str,
    },
    BuiltinImpl {
        implementation: String,
        method: String,
        receiver: rils_builtins::ReceiverMode,
        target: Type,
    },
    TraitDefault {
        trait_name: &'static str,
        method: &'static str,
        receiver: rils_builtins::ReceiverMode,
    },
    Native {
        symbol: &'static str,
        receiver: Option<rils_builtins::ReceiverMode>,
    },
    NumericIntrinsic {
        symbol: &'static str,
        receiver: Option<rils_builtins::ReceiverMode>,
    },
    Host {
        path: String,
    },
    Import {
        name: String,
        signature: FunctionSignature,
        capability: String,
    },
}

/// Nominal identity of a type used in a field projection or a pattern. Source locations
/// include the source ID, so sibling modules may freely reuse type names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NominalOwner {
    Source {
        name: std::sync::Arc<str>,
        declaration: Span,
    },
    Builtin(&'static str),
    Host(std::sync::Arc<str>),
}

/// Declaration identity used by existing resolved-field consumers.
pub use NominalOwner as RecordOwner;

impl NominalOwner {
    pub fn name(&self) -> &str {
        match self {
            Self::Source { name, .. } | Self::Host(name) => name,
            Self::Builtin(name) => name,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedField {
    pub owner: NominalOwner,
    /// Declaration order is shared by all instantiations. Byte offsets are not.
    pub index: usize,
}

/// Semantic side tables produced by frontend analysis.
///
/// Syntax remains immutable. Later stages use expression identities to query
/// inferred types and resolved callees instead of repeating name lookup.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TypeckResults {
    // An arm's expression ID also identifies its pattern in cloned function bodies.
    // Only arms with resolved constants or contextual literals need a replacement pattern.
    pub(crate) resolved_patterns: HashMap<ExprId, std::sync::Arc<crate::ast::Pattern>>,
    executable_patterns: HashMap<ExprId, std::sync::Arc<ResolvedPattern>>,
    pub callable_capabilities: CallableCapabilities,
    pub(crate) function_signatures: HashMap<Span, Type>,
    expression_ids: ExpressionIds,
    expression_types: HashMap<ExprId, Type>,
    resolved_calls: HashMap<ExprId, ResolvedCall>,
    resolved_values: HashMap<ExprId, DefId>,
    resolved_fields: HashMap<ExprId, ResolvedField>,
}

impl TypeckResults {
    pub(crate) fn set_expression_types(
        &mut self,
        expression_ids: ExpressionIds,
        expression_types: HashMap<ExprId, Type>,
    ) {
        self.expression_ids = expression_ids;
        self.expression_types = expression_types;
    }

    /// Returns every expression whose syntax range is `span`, in AST visit order.
    ///
    /// A source range is a diagnostic location rather than a semantic identity,
    /// so generated or recovered syntax can legitimately produce multiple IDs.
    pub fn expression_ids_at(&self, span: Span) -> &[ExprId] {
        self.expression_ids.at(span)
    }

    pub fn expression_span(&self, id: ExprId) -> Option<Span> {
        self.expression_ids.span(id)
    }

    pub fn expression_type(&self, id: ExprId) -> Option<&Type> {
        self.expression_types.get(&id)
    }

    pub fn arm_pattern<'a>(
        &'a self,
        identities: &ExpressionIdentityMap,
        arm: &'a crate::ast::MatchArm,
    ) -> &'a crate::ast::Pattern {
        if self.resolved_patterns.is_empty() {
            return &arm.pattern;
        }
        identities
            .get(&arm.expression)
            .and_then(|id| self.resolved_patterns.get(&id))
            .map_or(&arm.pattern, std::sync::Arc::as_ref)
    }

    pub fn executable_pattern(&self, arm: ExprId) -> Option<&ResolvedPattern> {
        self.executable_patterns.get(&arm).map(AsRef::as_ref)
    }

    /// Inferred declaration signature keyed by the immutable source body.
    pub fn function_signature(&self, body: Span) -> Option<&Type> {
        self.function_signatures.get(&body)
    }

    pub fn expression_type_ending_at(
        &self,
        source: SourceId,
        end: usize,
    ) -> Option<(ExprId, &Type)> {
        self.expression_types
            .iter()
            .filter_map(|(id, ty)| Some((*id, self.expression_span(*id)?, ty)))
            .filter(|(_, span, _)| span.source == source && span.end == end)
            .max_by_key(|(_, span, _)| span.start)
            .map(|(id, _, ty)| (id, ty))
    }

    pub fn resolved_call(&self, id: ExprId) -> Option<&ResolvedCall> {
        self.resolved_calls.get(&id)
    }

    pub fn has_trait_default_calls(&self) -> bool {
        self.resolved_calls
            .values()
            .any(|call| matches!(call, ResolvedCall::TraitDefault { .. }))
    }

    pub fn has_builtin_impl_calls(&self) -> bool {
        self.resolved_calls
            .values()
            .any(|call| matches!(call, ResolvedCall::BuiltinImpl { .. }))
    }

    pub fn resolved_value(&self, id: ExprId) -> Option<DefId> {
        self.resolved_values.get(&id).copied()
    }

    pub fn resolved_field(&self, id: ExprId) -> Option<&ResolvedField> {
        self.resolved_fields.get(&id)
    }

    pub fn resolved_call_containing(
        &self,
        source: SourceId,
        offset: usize,
    ) -> Option<(ExprId, &ResolvedCall)> {
        self.resolved_calls
            .iter()
            .filter_map(|(id, call)| Some((*id, self.expression_span(*id)?, call)))
            .filter(|(_, span, _)| {
                span.source == source && span.start <= offset && offset <= span.end
            })
            .min_by_key(|(_, span, _)| span.end.saturating_sub(span.start))
            .map(|(id, _, call)| (id, call))
    }

    pub(crate) fn extend(&mut self, other: Self) {
        self.callable_capabilities
            .extend(other.callable_capabilities);
        self.function_signatures.extend(other.function_signatures);
        self.resolved_patterns.extend(other.resolved_patterns);
        self.executable_patterns.extend(other.executable_patterns);
        self.expression_ids.extend(other.expression_ids);
        self.expression_types.extend(other.expression_types);
        self.resolved_calls.extend(other.resolved_calls);
        self.resolved_values.extend(other.resolved_values);
        self.resolved_fields.extend(other.resolved_fields);
    }

    pub(crate) fn resolve_call(&mut self, id: ExprId, call: ResolvedCall) {
        self.resolved_calls.insert(id, call);
    }

    fn resolve_value(&mut self, id: ExprId, definition: DefId) {
        self.resolved_values.insert(id, definition);
    }
}

fn qualified_name(namespace: &[String], name: &str) -> String {
    if namespace.is_empty() || name.contains("::") {
        name.to_owned()
    } else {
        format!("{}::{name}", namespace.join("::"))
    }
}

fn contextual_name(namespace: &[String], self_type: Option<&str>, name: &str) -> String {
    if name == "Self" {
        return self_type.unwrap_or(name).to_owned();
    }
    if let Some(suffix) = name.strip_prefix("Self::") {
        return self_type
            .map(|self_type| format!("{self_type}::{suffix}"))
            .unwrap_or_else(|| name.to_owned());
    }
    if let Some(name) = name.strip_prefix("crate::") {
        return name.to_owned();
    }
    if let Some(name) = name.strip_prefix("self::") {
        return qualified_name(namespace, name);
    }
    if name.starts_with("super::") {
        let mut parent = namespace.to_vec();
        let mut remainder = name;
        while let Some(stripped) = remainder.strip_prefix("super::") {
            parent.pop();
            remainder = stripped;
        }
        return qualified_name(&parent, remainder);
    }
    qualified_name(namespace, name)
}

fn member_span(span: Span, name: &str) -> Span {
    Span::in_source(span.source, span.end.saturating_sub(name.len()), span.end)
}

#[cfg(test)]
#[path = "../tests/unit/semantic.rs"]
mod tests;