lisette-semantics 0.2.12

Little language inspired by Rust that compiles to Go
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
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

use diagnostics::{PatternIssue, UnusedExpressionKind};
use syntax::ast::{BindingId, BindingKind, DeadCodeCause, Span};
use syntax::types::Type;

#[derive(Debug, Default)]
pub struct BindingIdAllocator {
    next: AtomicU32,
}

impl BindingIdAllocator {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn reserve(&self) -> BindingId {
        self.next.fetch_add(1, Ordering::Relaxed)
    }

    pub fn snapshot(&self) -> BindingId {
        self.next.load(Ordering::Relaxed)
    }
}

#[derive(Debug)]
pub struct Facts {
    allocator: Arc<BindingIdAllocator>,

    // LSP-consumed; reshaping these affects crates/lsp/.
    pub bindings: HashMap<BindingId, BindingFact>,
    pub usages: Vec<Usage>,
    usage_set: HashSet<(Span, Span)>,

    // Lint-support facts: read by reference by passes::lints (mostly
    // from_facts; interface_satisfied_methods by ref_graph).
    pub dead_code: Vec<DeadCodeFact>,
    pub pattern_issues: Vec<PatternIssue>,
    pub unused_expressions: Vec<UnusedExpressionFact>,
    pub discarded_tail_expressions: Vec<DiscardedTailFact>,
    pub overused_references: Vec<OverusedReferenceFact>,
    pub unused_type_params: Vec<UnusedTypeParamFact>,
    pub type_params_only_in_bound: Vec<TypeParamOnlyInBoundFact>,
    pub always_failing_try_blocks: Vec<Span>,
    pub expression_only_fstrings: Vec<Span>,
    pub interface_satisfied_methods: HashMap<(String, String), Vec<Span>>,

    // Drained by passes::deferred via mem::take.
    pub generic_call_checks: Vec<GenericCallCheck>,
    pub empty_collection_checks: Vec<EmptyCollectionCheck>,
    pub statement_tail_checks: Vec<StatementTailCheck>,

    /// Suppresses contradictory lints from or-patterns whose binding sets disagree.
    pub or_pattern_error_spans: HashSet<Span>,
}

#[derive(Debug, Clone)]
pub struct GenericCallCheck {
    pub return_ty: Type,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct EmptyCollectionCheck {
    pub name: String,
    pub ty: Type,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct StatementTailCheck {
    pub expected_ty: Type,
    pub span: Span,
}

impl Facts {
    pub fn new(allocator: Arc<BindingIdAllocator>) -> Self {
        Self {
            allocator,
            bindings: HashMap::default(),
            dead_code: Vec::new(),
            pattern_issues: Vec::new(),
            unused_expressions: Vec::new(),
            discarded_tail_expressions: Vec::new(),
            overused_references: Vec::new(),
            unused_type_params: Vec::new(),
            type_params_only_in_bound: Vec::new(),
            always_failing_try_blocks: Vec::new(),
            expression_only_fstrings: Vec::new(),
            generic_call_checks: Vec::new(),
            empty_collection_checks: Vec::new(),
            statement_tail_checks: Vec::new(),
            or_pattern_error_spans: HashSet::default(),
            usages: Vec::new(),
            usage_set: HashSet::default(),
            interface_satisfied_methods: HashMap::default(),
        }
    }

    pub fn add_binding(
        &mut self,
        name: String,
        span: Span,
        kind: BindingKind,
        is_typedef: bool,
        is_struct_field: bool,
        is_as_alias: bool,
    ) -> BindingId {
        let id = self.allocator.reserve();
        self.bindings.insert(
            id,
            BindingFact {
                name,
                span,
                kind,
                used: false,
                mutated: false,
                is_typedef,
                is_struct_field,
                is_as_alias,
            },
        );
        id
    }

    pub fn mark_used(&mut self, id: BindingId) {
        if let Some(fact) = self.bindings.get_mut(&id) {
            fact.used = true;
        }
    }

    pub fn mark_mutated(&mut self, id: BindingId) {
        if let Some(fact) = self.bindings.get_mut(&id) {
            fact.mutated = true;
        }
    }

    pub fn binding_checkpoint(&self) -> BindingId {
        self.allocator.snapshot()
    }

    pub fn remove_bindings_from(&mut self, checkpoint: BindingId) {
        self.bindings.retain(|id, _| *id < checkpoint);
    }

    pub fn add_dead_code(&mut self, span: Span, cause: DeadCodeCause) {
        self.dead_code.push(DeadCodeFact { span, cause });
    }

    pub fn add_overused_reference(&mut self, span: Span, name: Option<String>) {
        self.overused_references
            .push(OverusedReferenceFact { span, name });
    }

    pub fn add_always_failing_try_block(&mut self, span: Span) {
        self.always_failing_try_blocks.push(span);
    }

    pub fn add_expression_only_fstring(&mut self, span: Span) {
        self.expression_only_fstrings.push(span);
    }

    pub fn add_usage(&mut self, usage_span: Span, definition_span: Span) {
        if self.usage_set.insert((usage_span, definition_span)) {
            self.usages.push(Usage {
                usage_span,
                definition_span,
            });
        }
    }

    pub fn mark_method_used_for_interface(
        &mut self,
        module_id: String,
        method_name: String,
        usage_span: Span,
    ) {
        self.interface_satisfied_methods
            .entry((module_id, method_name))
            .or_default()
            .push(usage_span);
    }

    pub fn absorb_local_facts(&mut self, local: LocalFacts) {
        let LocalFacts {
            unused_expressions,
            discarded_tail_expressions,
            unused_type_params,
            type_params_only_in_bound,
        } = local;
        self.unused_expressions.extend(unused_expressions);
        self.discarded_tail_expressions
            .extend(discarded_tail_expressions);
        self.unused_type_params.extend(unused_type_params);
        self.type_params_only_in_bound
            .extend(type_params_only_in_bound);
    }

    pub fn merge(&mut self, other: Facts) {
        debug_assert!(
            Arc::ptr_eq(&self.allocator, &other.allocator),
            "Facts::merge requires a shared BindingIdAllocator",
        );

        let Facts {
            allocator: _,
            bindings,
            dead_code,
            pattern_issues,
            unused_expressions,
            discarded_tail_expressions,
            overused_references,
            unused_type_params,
            type_params_only_in_bound,
            always_failing_try_blocks,
            expression_only_fstrings,
            generic_call_checks,
            empty_collection_checks,
            statement_tail_checks,
            or_pattern_error_spans,
            usages,
            usage_set: _,
            interface_satisfied_methods,
        } = other;

        self.bindings.extend(bindings);
        self.dead_code.extend(dead_code);
        self.pattern_issues.extend(pattern_issues);
        self.unused_expressions.extend(unused_expressions);
        self.discarded_tail_expressions
            .extend(discarded_tail_expressions);
        self.overused_references.extend(overused_references);
        self.unused_type_params.extend(unused_type_params);
        self.type_params_only_in_bound
            .extend(type_params_only_in_bound);
        self.always_failing_try_blocks
            .extend(always_failing_try_blocks);
        self.expression_only_fstrings
            .extend(expression_only_fstrings);
        self.generic_call_checks.extend(generic_call_checks);
        self.empty_collection_checks.extend(empty_collection_checks);
        self.statement_tail_checks.extend(statement_tail_checks);
        self.or_pattern_error_spans.extend(or_pattern_error_spans);

        self.usages.reserve(usages.len());
        self.usage_set.reserve(usages.len());
        for Usage {
            usage_span,
            definition_span,
        } in usages
        {
            self.add_usage(usage_span, definition_span);
        }

        for (key, spans) in interface_satisfied_methods {
            self.interface_satisfied_methods
                .entry(key)
                .or_default()
                .extend(spans);
        }
    }
}

#[derive(Debug, Default)]
pub struct LocalFacts {
    pub unused_expressions: Vec<UnusedExpressionFact>,
    pub discarded_tail_expressions: Vec<DiscardedTailFact>,
    pub unused_type_params: Vec<UnusedTypeParamFact>,
    pub type_params_only_in_bound: Vec<TypeParamOnlyInBoundFact>,
}

impl LocalFacts {
    pub fn add_unused_expression(&mut self, span: Span, kind: UnusedExpressionKind) {
        self.unused_expressions
            .push(UnusedExpressionFact { span, kind });
    }

    pub fn add_discarded_tail(
        &mut self,
        span: Span,
        return_type: String,
        expected_span: Span,
        expected_type: String,
    ) {
        self.discarded_tail_expressions.push(DiscardedTailFact {
            span,
            return_type,
            expected_span,
            expected_type,
        });
    }

    pub fn add_unused_type_param(&mut self, name: String, span: Span) {
        self.unused_type_params
            .push(UnusedTypeParamFact { name, span });
    }

    pub fn add_type_param_only_in_bound(&mut self, name: String, span: Span) {
        self.type_params_only_in_bound
            .push(TypeParamOnlyInBoundFact { name, span });
    }
}

#[derive(Debug, Clone)]
pub struct BindingFact {
    pub name: String,
    pub span: Span,
    pub kind: BindingKind,
    pub used: bool,
    pub mutated: bool,
    pub is_typedef: bool,
    /// If true, this binding is a shorthand in a struct pattern (e.g., `Point { x }`)
    pub is_struct_field: bool,
    /// If true, this binding was introduced by an `as` alias (e.g., `Point { .. } as p`)
    pub is_as_alias: bool,
}

#[derive(Debug, Clone)]
pub struct DeadCodeFact {
    pub span: Span,
    pub cause: DeadCodeCause,
}

#[derive(Debug, Clone)]
pub struct UnusedExpressionFact {
    pub span: Span,
    pub kind: UnusedExpressionKind,
}

#[derive(Debug, Clone)]
pub struct DiscardedTailFact {
    pub span: Span,
    pub return_type: String,
    pub expected_span: Span,
    pub expected_type: String,
}

#[derive(Debug, Clone)]
pub struct OverusedReferenceFact {
    pub span: Span,
    pub name: Option<String>,
}

#[derive(Debug, Clone)]
pub struct UnusedTypeParamFact {
    pub name: String,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct TypeParamOnlyInBoundFact {
    pub name: String,
    pub span: Span,
}

/// Records a usage of a symbol, linking the usage location to its definition.
/// Used by LSP for find-references.
#[derive(Debug, Clone)]
pub struct Usage {
    pub usage_span: Span,
    pub definition_span: Span,
}

#[cfg(test)]
mod tests {
    use super::*;
    use syntax::ast::BindingKind;

    fn span(offset: u32) -> Span {
        Span::new(0, offset, 1)
    }

    #[test]
    fn merge_preserves_unique_binding_ids_across_tasks() {
        let allocator = Arc::new(BindingIdAllocator::new());
        let mut a = Facts::new(allocator.clone());
        let mut b = Facts::new(allocator.clone());

        let a_id = a.add_binding(
            "a".into(),
            span(0),
            BindingKind::Let { mutable: false },
            false,
            false,
            false,
        );
        let b_id = b.add_binding(
            "b".into(),
            span(1),
            BindingKind::Let { mutable: false },
            false,
            false,
            false,
        );
        assert_ne!(a_id, b_id);

        a.merge(b);
        assert_eq!(a.bindings.len(), 2);
        assert!(a.bindings.contains_key(&a_id));
        assert!(a.bindings.contains_key(&b_id));
    }

    #[test]
    fn merge_extends_vec_facts() {
        let allocator = Arc::new(BindingIdAllocator::new());
        let mut a = Facts::new(allocator.clone());
        let mut b = Facts::new(allocator);

        a.add_always_failing_try_block(span(0));
        b.add_always_failing_try_block(span(1));
        b.add_always_failing_try_block(span(2));

        a.merge(b);
        assert_eq!(a.always_failing_try_blocks.len(), 3);
    }

    #[test]
    fn merge_deduplicates_usages() {
        let allocator = Arc::new(BindingIdAllocator::new());
        let mut a = Facts::new(allocator.clone());
        let mut b = Facts::new(allocator);

        a.add_usage(span(10), span(0));
        b.add_usage(span(10), span(0));
        b.add_usage(span(20), span(0));

        a.merge(b);
        assert_eq!(a.usages.len(), 2);
    }

    #[test]
    fn merge_deduplicates_or_pattern_error_spans() {
        let allocator = Arc::new(BindingIdAllocator::new());
        let mut a = Facts::new(allocator.clone());
        let mut b = Facts::new(allocator);

        a.or_pattern_error_spans.insert(span(0));
        b.or_pattern_error_spans.insert(span(0));
        b.or_pattern_error_spans.insert(span(1));

        a.merge(b);
        assert_eq!(a.or_pattern_error_spans.len(), 2);
    }

    #[test]
    fn absorb_local_facts_extends_all_four_streams() {
        let allocator = Arc::new(BindingIdAllocator::new());
        let mut facts = Facts::new(allocator);

        let mut local = LocalFacts::default();
        local.add_unused_expression(span(0), UnusedExpressionKind::Value);
        local.add_discarded_tail(span(1), "Int".into(), span(2), "Unit".into());
        local.add_unused_type_param("T".into(), span(3));
        local.add_type_param_only_in_bound("U".into(), span(4));

        facts.absorb_local_facts(local);

        assert_eq!(facts.unused_expressions.len(), 1);
        assert_eq!(facts.discarded_tail_expressions.len(), 1);
        assert_eq!(facts.unused_type_params.len(), 1);
        assert_eq!(facts.type_params_only_in_bound.len(), 1);
    }

    #[test]
    fn merge_concatenates_interface_method_spans() {
        let allocator = Arc::new(BindingIdAllocator::new());
        let mut a = Facts::new(allocator.clone());
        let mut b = Facts::new(allocator);

        a.mark_method_used_for_interface("m".into(), "f".into(), span(0));
        b.mark_method_used_for_interface("m".into(), "f".into(), span(1));
        b.mark_method_used_for_interface("m".into(), "g".into(), span(2));

        a.merge(b);
        assert_eq!(a.interface_satisfied_methods.len(), 2);
        assert_eq!(
            a.interface_satisfied_methods[&("m".into(), "f".into())].len(),
            2
        );
        assert_eq!(
            a.interface_satisfied_methods[&("m".into(), "g".into())].len(),
            1
        );
    }
}