-
Notifications
You must be signed in to change notification settings - Fork 741
Expand file tree
/
Copy pathcompute.rs
More file actions
4937 lines (4629 loc) · 198 KB
/
compute.rs
File metadata and controls
4937 lines (4629 loc) · 198 KB
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module is responsible for computing the semantic model of expressions and statements in
//! the code, while type checking.
//! It is invoked by queries for function bodies and other code blocks.
use core::panic;
use std::ops::Deref;
use std::sync::Arc;
use ast::PathSegment;
use cairo_lang_defs::db::{DefsGroup, get_all_path_leaves, validate_attributes_flat};
use cairo_lang_defs::diagnostic_utils::StableLocation;
use cairo_lang_defs::ids::{
FunctionTitleId, GenericKind, LanguageElementId, LocalVarLongId, LookupItemId, MemberId,
ModuleId, ModuleItemId, NamedLanguageElementId, StatementConstLongId, StatementItemId,
StatementUseLongId, TraitFunctionId, TraitId, VarId,
};
use cairo_lang_defs::plugin::{InlineMacroExprPlugin, MacroPluginMetadata};
use cairo_lang_diagnostics::{DiagnosticNote, Maybe, skip_diagnostic};
use cairo_lang_filesystem::cfg::CfgSet;
use cairo_lang_filesystem::db::FilesGroup;
use cairo_lang_filesystem::ids::{
CodeMapping, CodeOrigin, FileKind, FileLongId, SmolStrId, VirtualFile,
};
use cairo_lang_filesystem::span::TextOffset;
use cairo_lang_parser::db::ParserGroup;
use cairo_lang_proc_macros::DebugWithDb;
use cairo_lang_syntax::attribute::consts::UNUSED_VARIABLES;
use cairo_lang_syntax::node::ast::{
BinaryOperator, BlockOrIf, ConditionListAnd, ExprPtr, OptionReturnTypeClause, PatternListOr,
PatternStructParam, TerminalIdentifier, UnaryOperator,
};
use cairo_lang_syntax::node::helpers::{GetIdentifier, PathSegmentEx, QueryAttrs};
use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_syntax::node::{Terminal, TypedStablePtr, TypedSyntaxNode, ast};
use cairo_lang_utils::ordered_hash_map::{Entry, OrderedHashMap};
use cairo_lang_utils::ordered_hash_set::OrderedHashSet;
use cairo_lang_utils::unordered_hash_map::UnorderedHashMap;
use cairo_lang_utils::unordered_hash_set::UnorderedHashSet;
use cairo_lang_utils::{
self as utils, Intern, OptionHelper, extract_matches, require, try_extract_matches,
};
use itertools::{Itertools, chain, zip_eq};
use num_bigint::BigInt;
use num_traits::ToPrimitive;
use salsa::Database;
use super::inference::canonic::ResultNoErrEx;
use super::inference::conform::InferenceConform;
use super::inference::infers::InferenceEmbeddings;
use super::inference::{Inference, InferenceData, InferenceError};
use super::objects::*;
use super::pattern::{
Pattern, PatternEnumVariant, PatternFixedSizeArray, PatternLiteral, PatternMissing,
PatternOtherwise, PatternTuple, PatternVariable, PatternWrappingInfo,
};
use crate::corelib::{
self, CorelibSemantic, core_binary_operator, core_bool_ty, core_unary_operator,
false_literal_expr, get_usize_ty, never_ty, true_literal_expr, try_extract_box_inner_type,
try_get_core_ty_by_name, unit_expr, unit_ty, unwrap_error_propagation_type, validate_literal,
};
use crate::diagnostic::SemanticDiagnosticKind::{self, *};
use crate::diagnostic::{
ElementKind, MultiArmExprKind, NotFoundItemType, SemanticDiagnostics,
SemanticDiagnosticsBuilder, TraitInferenceErrors, UnsupportedOutsideOfFunctionFeatureName,
};
use crate::expr::inference::solver::SolutionSet;
use crate::expr::inference::{ImplVarTraitItemMappings, InferenceId};
use crate::items::constant::{
ConstValue, ConstantSemantic, resolve_const_expr_and_evaluate, validate_const_expr,
};
use crate::items::enm::{EnumSemantic, SemanticEnumEx};
use crate::items::feature_kind::{FeatureConfig, FeatureConfigRestore};
use crate::items::functions::{FunctionsSemantic, function_signature_params};
use crate::items::generics::GenericParamSemantic;
use crate::items::imp::{
DerefInfo, ImplLookupContextId, ImplSemantic, filter_candidate_traits, infer_impl_by_self,
};
use crate::items::macro_declaration::{
MacroDeclarationSemantic, MatcherContext, expand_macro_rule, is_macro_rule_match,
};
use crate::items::modifiers::compute_mutability;
use crate::items::module::ModuleSemantic;
use crate::items::structure::StructSemantic;
use crate::items::trt::TraitSemantic;
use crate::items::visibility;
use crate::keyword::MACRO_CALL_SITE;
use crate::lsp_helpers::LspHelpers;
use crate::resolve::{
AsSegments, EnrichedMembers, EnrichedTypeMemberAccess, ResolutionContext, ResolvedConcreteItem,
ResolvedGenericItem, Resolver, ResolverMacroData,
};
use crate::semantic::{self, Binding, FunctionId, LocalVariable, TypeId, TypeLongId};
use crate::substitution::SemanticRewriter;
use crate::types::{
ClosureTypeLongId, ConcreteTypeId, add_type_based_diagnostics, are_coupons_enabled,
extract_fixed_size_array_size, peel_snapshots, peel_snapshots_ex, resolve_type_ex,
verify_fixed_size_array_size, wrap_in_snapshots,
};
use crate::usage::Usages;
use crate::{
ConcreteEnumId, ConcreteVariant, GenericArgumentId, GenericParam, LocalItem, Member,
Mutability, Parameter, PatternStringLiteral, PatternStruct, Signature, StatementItemKind,
};
/// The information of a macro expansion.
#[derive(Debug, Clone, PartialEq, Eq, salsa::Update)]
struct MacroExpansionInfo<'db> {
/// The code mappings for this expansion.
mappings: Arc<[CodeMapping]>,
/// The kind of macro the expansion is from.
kind: MacroKind,
/// The variables that should be exposed to the parent scope after the macro expansion.
/// This is used for unhygienic macros.
vars_to_expose: Vec<(SmolStrId<'db>, Binding<'db>)>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExpansionOffset(TextOffset);
impl ExpansionOffset {
/// Creates a new origin offset.
pub fn new(offset: TextOffset) -> Self {
Self(offset)
}
/// Returns the origin of the position that was expanded at the given offset, if any.
pub fn mapped(self, mappings: &[CodeMapping]) -> Option<Self> {
let mapping = mappings
.iter()
.find(|mapping| mapping.span.start <= self.0 && self.0 <= mapping.span.end)?;
Some(Self::new(match mapping.origin {
CodeOrigin::Start(offset) => offset.add_width(self.0 - mapping.span.start),
CodeOrigin::Span(span) | CodeOrigin::CallSite(span) => span.start,
}))
}
}
/// Describes the origin and hygiene behavior of a macro expansion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroKind {
/// A user-defined macro, expanded with standard hygiene.
UserDefined,
/// A plugin macro.
Plugin,
/// An unhygienic macro, whose variables are injected into the parent scope.
Unhygienic,
}
/// Expression with its id.
#[derive(Debug, Clone)]
pub struct ExprAndId<'db> {
pub expr: Expr<'db>,
pub id: ExprId,
}
impl<'db> Deref for ExprAndId<'db> {
type Target = Expr<'db>;
fn deref(&self) -> &Self::Target {
&self.expr
}
}
#[derive(Debug, Clone)]
pub struct PatternAndId<'db> {
pub pattern: Pattern<'db>,
pub id: PatternId,
}
impl<'db> Deref for PatternAndId<'db> {
type Target = Pattern<'db>;
fn deref(&self) -> &Self::Target {
&self.pattern
}
}
/// An argument in a function call, with optional name and modifiers.
#[derive(Debug, Clone)]
pub struct NamedArg<'db> {
/// The expression for this argument.
expr: ExprAndId<'db>,
/// The name of the argument, if provided (for named arguments like `foo: value`).
name: Option<ast::TerminalIdentifier<'db>>,
/// The mutability modifiers (`ref` or `mut`) applied to this argument.
mutability: Mutability,
/// Whether this argument can be passed as a temporary reference.
/// This is only true for `ref self` in method calls on temporary expressions
/// (e.g., `make_foo().method()` where `method` takes `ref self`).
is_temp_ref_allowed: bool,
}
impl<'db> NamedArg<'db> {
/// Creates a new argument with the given expression and modifiers.
/// This is the common case for most function arguments.
fn new(expr: ExprAndId<'db>, modifiers: Mutability) -> Self {
Self { expr, name: None, mutability: modifiers, is_temp_ref_allowed: false }
}
/// Creates a new immutable argument (no modifiers).
fn value(expr: ExprAndId<'db>) -> Self {
Self::new(expr, Mutability::Immutable)
}
/// Creates an argument that allows temporary references.
/// Used for `ref self` in method calls on temporary expressions.
fn temp_reference(expr: ExprAndId<'db>) -> Self {
Self { expr, name: None, mutability: Mutability::Reference, is_temp_ref_allowed: true }
}
/// Creates an argument with a name (for named arguments like `foo: value`).
fn named(
expr: ExprAndId<'db>,
name: Option<ast::TerminalIdentifier<'db>>,
modifiers: Mutability,
) -> Self {
Self { expr, name, mutability: modifiers, is_temp_ref_allowed: false }
}
}
pub enum ContextFunction<'db> {
Global,
Function(Maybe<FunctionId<'db>>),
}
/// Context inside loops or closures.
#[derive(Debug, Clone)]
struct InnerContext<'db> {
/// The return type in the current context.
return_type: TypeId<'db>,
/// The kind of inner context.
kind: InnerContextKind<'db>,
}
/// Kinds of inner context.
#[derive(Debug, Clone)]
enum InnerContextKind<'db> {
/// Context inside a `loop`.
Loop { type_merger: FlowMergeTypeHelper<'db> },
/// Context inside a `while` loop.
While,
/// Context inside a `for` loop.
For,
/// Context inside a `closure`.
Closure,
}
/// The result of expanding an inline macro.
#[derive(Debug, Clone)]
struct InlineMacroExpansion<'db> {
pub content: Arc<str>,
pub name: String,
pub info: MacroExpansionInfo<'db>,
}
/// Context for computing the semantic model of expression trees.
pub struct ComputationContext<'ctx, 'mt> {
pub db: &'ctx dyn Database,
pub diagnostics: &'mt mut SemanticDiagnostics<'ctx>,
pub resolver: &'mt mut Resolver<'ctx>,
/// Tracks variable definitions and their mutability state.
pub variable_tracker: VariableTracker<'ctx>,
signature: Option<&'mt Signature<'ctx>>,
environment: Box<Environment<'ctx>>,
/// Arenas of semantic objects.
pub arenas: Arenas<'ctx>,
function_id: ContextFunction<'ctx>,
inner_ctx: Option<InnerContext<'ctx>>,
cfg_set: Arc<CfgSet>,
/// Whether to look for closures when calling variables.
/// TODO(TomerStarkware): Remove this once we disallow calling shadowed functions.
are_closures_in_context: bool,
/// Whether variables defined in the current macro scope should be injected into the parent
/// scope.
macro_defined_var_unhygienic: bool,
}
impl<'ctx, 'mt> ComputationContext<'ctx, 'mt> {
/// Creates a new computation context.
pub fn new(
db: &'ctx dyn Database,
diagnostics: &'mt mut SemanticDiagnostics<'ctx>,
resolver: &'mt mut Resolver<'ctx>,
signature: Option<&'mt Signature<'ctx>>,
environment: Environment<'ctx>,
function_id: ContextFunction<'ctx>,
) -> Self {
let cfg_set =
Arc::new(resolver.settings.cfg_set.as_ref().unwrap_or_else(|| db.cfg_set()).clone());
let mut variable_tracker = VariableTracker::default();
variable_tracker.extend_from_environment(&environment);
Self {
db,
diagnostics,
resolver,
signature,
environment: Box::new(environment),
arenas: Default::default(),
function_id,
variable_tracker,
inner_ctx: None,
cfg_set,
are_closures_in_context: false,
macro_defined_var_unhygienic: false,
}
}
/// Creates a new computation context for a global scope.
pub fn new_global(
db: &'ctx dyn Database,
diagnostics: &'mt mut SemanticDiagnostics<'ctx>,
resolver: &'mt mut Resolver<'ctx>,
) -> Self {
Self::new(db, diagnostics, resolver, None, Environment::empty(), ContextFunction::Global)
}
/// Inserts a variable into both environment and variable tracker.
/// Returns the old value if the variable was already defined.
pub fn insert_variable(
&mut self,
name: SmolStrId<'ctx>,
var_def: Binding<'ctx>,
) -> Option<Binding<'ctx>> {
// Ignore re-definitions in the variable tracker, diagnostics will be issued by the caller
// using this method's return value.
let _ = self.variable_tracker.insert(var_def.clone());
self.environment.variables.insert(name, var_def)
}
/// Runs a function with a modified context, with a new environment for a subscope.
/// This environment holds no variables of its own, but points to the current environment as a
/// parent. Used for blocks of code that introduce a new scope like function bodies, if
/// blocks, loops, etc.
fn run_in_subscope<T, F>(&mut self, f: F) -> T
where
F: FnOnce(&mut Self) -> T,
{
self.run_in_subscope_ex(f, None)
}
/// Similar to run_in_subscope, but for macro expanded code. It creates a new environment
/// that points to the current environment as a parent, and also contains the macro expansion
/// data. When looking up variables, we will get out of the macro expansion environment if
/// and only if the text was originated from expanding a placeholder.
fn run_in_macro_subscope<T, F>(
&mut self,
operation: F,
macro_info: MacroExpansionInfo<'ctx>,
) -> T
where
F: FnOnce(&mut Self) -> T,
{
let prev_macro_hygiene_kind = self.macro_defined_var_unhygienic;
let prev_default_module_allowed = self.resolver.default_module_allowed;
match macro_info.kind {
MacroKind::Unhygienic => {
self.macro_defined_var_unhygienic = true;
}
MacroKind::Plugin => {
self.resolver.set_default_module_allowed(true);
}
MacroKind::UserDefined => {}
}
let result = self.run_in_subscope_ex(operation, Some(macro_info));
self.macro_defined_var_unhygienic = prev_macro_hygiene_kind;
self.resolver.set_default_module_allowed(prev_default_module_allowed);
result
}
/// Runs a function with a modified context, with a new environment for a subscope.
/// Shouldn't be called directly, use [Self::run_in_subscope] or [Self::run_in_macro_subscope]
/// instead.
fn run_in_subscope_ex<T, F>(&mut self, f: F, macro_info: Option<MacroExpansionInfo<'ctx>>) -> T
where
F: FnOnce(&mut Self) -> T,
{
// Push an environment to the stack.
let parent = std::mem::replace(&mut self.environment, Environment::empty().into());
self.environment.parent = Some(parent);
self.environment.macro_info = macro_info;
let res = f(self);
// Pop the environment from the stack.
let parent = self.environment.parent.take().unwrap();
let mut closed = std::mem::replace(&mut self.environment, parent);
let parent = &mut self.environment;
if let Some(macro_info) = closed.macro_info {
for (name, binding) in macro_info.vars_to_expose {
// Exposed variables are considered moved in the closed scope, as they still may be
// used later.
if !closed.used_variables.insert(binding.id()) {
// In case a variable was already marked as used in the closed environment, it
// means it was actually used, and is marked as used in the environment it is
// moved to.
parent.used_variables.insert(binding.id());
}
if let Some(old_var) = parent.variables.insert(name, binding.clone()) {
add_unused_binding_warning(
self.diagnostics,
self.db,
&parent.used_variables,
name,
&old_var,
&self.resolver.data.feature_config,
);
}
if let Some(parent_macro_info) = parent.macro_info.as_mut() {
parent_macro_info.vars_to_expose.push((name, binding));
}
}
}
for (name, binding) in closed.variables {
add_unused_binding_warning(
self.diagnostics,
self.db,
&closed.used_variables,
name,
&binding,
&self.resolver.data.feature_config,
);
}
// Adds warning for unused items if required.
for (ty_name, statement_ty) in closed.use_items {
if !closed.used_use_items.contains(&ty_name) && !ty_name.long(self.db).starts_with('_')
{
self.diagnostics.report(statement_ty.stable_ptr, UnusedUse);
}
}
res
}
/// Returns the return type in the current context if available.
fn get_return_type(&mut self) -> Option<TypeId<'ctx>> {
if let Some(inner_ctx) = &self.inner_ctx {
return Some(inner_ctx.return_type);
}
if let Some(signature) = self.signature {
return Some(signature.return_type);
}
None
}
fn reduce_ty(&mut self, ty: TypeId<'ctx>) -> TypeId<'ctx> {
self.resolver.inference().rewrite(ty).no_err()
}
/// Applies inference rewriter to all the expressions in the computation context, and adds
/// errors on types from the final expressions.
pub fn apply_inference_rewriter_to_exprs(&mut self) {
let mut analyzed_types = UnorderedHashSet::<_>::default();
for (_id, expr) in &mut self.arenas.exprs {
self.resolver.inference().internal_rewrite(expr).no_err();
// Adding an error only once per type.
if analyzed_types.insert(expr.ty()) {
add_type_based_diagnostics(self.db, self.diagnostics, expr.ty(), &*expr);
}
}
}
/// Applies inference rewriter to all the rewritable things in the computation context.
fn apply_inference_rewriter(&mut self) {
self.apply_inference_rewriter_to_exprs();
for (_id, pattern) in &mut self.arenas.patterns {
self.resolver.inference().internal_rewrite(pattern).no_err();
}
for (_id, stmt) in &mut self.arenas.statements {
self.resolver.inference().internal_rewrite(stmt).no_err();
}
}
/// Returns whether the current context is inside a loop.
fn is_inside_loop(&self) -> bool {
let Some(inner_ctx) = &self.inner_ctx else {
return false;
};
match inner_ctx.kind {
InnerContextKind::Closure => false,
InnerContextKind::Loop { .. } | InnerContextKind::While | InnerContextKind::For => true,
}
}
/// Validates the features of the given item, then pushes them into the context.
/// IMPORTANT: Don't forget to restore through `restore_features`!
fn add_features_from_statement<Item: QueryAttrs<'ctx> + TypedSyntaxNode<'ctx>>(
&mut self,
item: &Item,
) -> FeatureConfigRestore<'ctx> {
validate_statement_attributes(self, item);
let crate_id = self.resolver.owning_crate_id;
self.resolver.extend_feature_config_from_item(self.db, crate_id, self.diagnostics, item)
}
/// Restores the feature config to its state before [Self::add_features_from_statement],
/// using the restoration state returned by that method.
fn restore_features(&mut self, feature_restore: FeatureConfigRestore<'ctx>) {
self.resolver.restore_feature_config(feature_restore);
}
}
/// Tracks variable definitions and their mutability state.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct VariableTracker<'ctx> {
/// Definitions of semantic variables.
semantic_defs: UnorderedHashMap<semantic::VarId<'ctx>, Binding<'ctx>>,
/// Mutable variables that have been referenced (lost mutability).
referenced_mut_vars: UnorderedHashMap<semantic::VarId<'ctx>, SyntaxStablePtrId<'ctx>>,
}
impl<'ctx> VariableTracker<'ctx> {
/// Extends the variable tracker from the variables present in the environment.
pub fn extend_from_environment(&mut self, environment: &Environment<'ctx>) {
self.semantic_defs
.extend(environment.variables.values().cloned().map(|var| (var.id(), var)));
}
/// Inserts a semantic definition for a variable.
/// Returns the old value if the variable was already defined.
pub fn insert(&mut self, var: Binding<'ctx>) -> Option<Binding<'ctx>> {
self.semantic_defs.insert(var.id(), var)
}
/// Returns true if the variable is currently mutable.
/// A variable is mutable only if declared mutable AND not referenced.
pub fn is_mut(&self, var_id: &semantic::VarId<'ctx>) -> bool {
self.semantic_defs
.get(var_id)
.is_some_and(|def| def.is_mut() && !self.referenced_mut_vars.contains_key(var_id))
}
/// Returns true if the expression is a variable or a member access of a mutable variable.
pub fn is_mut_expr(&self, expr: &ExprAndId<'ctx>) -> bool {
expr.as_member_path().is_some_and(|var| self.is_mut(&var.base_var()))
}
/// Reports a mutability error if the variable cannot be modified.
pub fn report_var_mutability_error(
&self,
db: &'ctx dyn Database,
diagnostics: &mut SemanticDiagnostics<'ctx>,
var_id: &semantic::VarId<'ctx>,
error_ptr: impl Into<SyntaxStablePtrId<'ctx>>,
immutable_diagnostic: SemanticDiagnosticKind<'ctx>,
) {
let Some(def) = self.semantic_defs.get(var_id) else {
return;
};
if !def.is_mut() {
diagnostics.report(error_ptr, immutable_diagnostic);
return;
}
if let Some(&referenced_at) = self.referenced_mut_vars.get(var_id) {
let note = DiagnosticNote::with_location(
"variable pointer taken here".into(),
StableLocation::new(referenced_at).span_in_file(db),
);
diagnostics.report(error_ptr, AssignmentToReprPtrVariable(vec![note]));
}
}
/// Marks an expression as pointed to if it refers to a mutable variable.
pub fn mark_referenced(
&mut self,
expr: &ExprAndId<'ctx>,
reference_location: SyntaxStablePtrId<'ctx>,
) {
if let Some(base_var) = expr.as_member_path().map(|path| path.base_var())
&& self.is_mut(&base_var)
{
// This insert happens only once, since `is_mut` returns false if already referenced.
let _ = self.referenced_mut_vars.insert(base_var, reference_location);
}
}
}
/// Adds warning for unused bindings if required.
fn add_unused_binding_warning<'db>(
diagnostics: &mut SemanticDiagnostics<'db>,
db: &'db dyn Database,
used_bindings: &UnorderedHashSet<VarId<'db>>,
name: SmolStrId<'db>,
binding: &Binding<'db>,
ctx_feature_config: &FeatureConfig<'db>,
) {
if !name.long(db).starts_with('_') && !used_bindings.contains(&binding.id()) {
match binding {
Binding::LocalItem(local_item) => match local_item.id {
StatementItemId::Constant(_) => {
diagnostics.report(binding.stable_ptr(db), UnusedConstant);
}
StatementItemId::Use(_) => {
diagnostics.report(binding.stable_ptr(db), UnusedUse);
}
},
Binding::LocalVar(local_var) => {
if !local_var.allow_unused
&& !ctx_feature_config
.allowed_lints
.contains(&SmolStrId::from(db, UNUSED_VARIABLES))
{
diagnostics.report(binding.stable_ptr(db), UnusedVariable);
}
}
Binding::Param(_) => {
if !ctx_feature_config
.allowed_lints
.contains(&SmolStrId::from(db, UNUSED_VARIABLES))
{
diagnostics.report(binding.stable_ptr(db), UnusedVariable);
}
}
}
}
}
// TODO(ilya): Change value to VarId.
pub type EnvVariables<'db> = OrderedHashMap<SmolStrId<'db>, Binding<'db>>;
type EnvItems<'db> = OrderedHashMap<SmolStrId<'db>, StatementGenericItemData<'db>>;
/// Struct that holds the resolved generic type of a statement item.
#[derive(Clone, Debug, PartialEq, Eq, DebugWithDb, salsa::Update)]
#[debug_db(dyn Database)]
struct StatementGenericItemData<'db> {
resolved_generic_item: ResolvedGenericItem<'db>,
stable_ptr: SyntaxStablePtrId<'db>,
}
/// A state which contains all the variables defined at the current resolver until now, and a
/// pointer to the parent environment.
#[derive(Clone, Debug, PartialEq, Eq, salsa::Update)]
pub struct Environment<'db> {
parent: Option<Box<Environment<'db>>>,
variables: EnvVariables<'db>,
used_variables: UnorderedHashSet<semantic::VarId<'db>>,
use_items: EnvItems<'db>,
used_use_items: UnorderedHashSet<SmolStrId<'db>>,
/// Information for macro in case the current environment was create by expanding a macro.
macro_info: Option<MacroExpansionInfo<'db>>,
}
impl<'db> Environment<'db> {
/// Adds a parameter to the environment.
pub fn add_param(
&mut self,
db: &'db dyn Database,
diagnostics: &mut SemanticDiagnostics<'db>,
semantic_param: Parameter<'db>,
ast_param: &ast::Param<'db>,
function_title_id: Option<FunctionTitleId<'db>>,
) -> Maybe<()> {
if let utils::ordered_hash_map::Entry::Vacant(entry) =
self.variables.entry(semantic_param.name)
{
entry.insert(Binding::Param(semantic_param));
Ok(())
} else {
Err(diagnostics.report(
ast_param.stable_ptr(db),
ParamNameRedefinition { function_title_id, param_name: semantic_param.name },
))
}
}
pub fn empty() -> Self {
Self {
parent: None,
variables: Default::default(),
used_variables: Default::default(),
use_items: Default::default(),
used_use_items: Default::default(),
macro_info: None,
}
}
}
/// Returns the requested item from the environment if it exists. Returns None otherwise.
pub fn get_statement_item_by_name<'db>(
env: &mut Environment<'db>,
item_name: SmolStrId<'db>,
) -> Option<ResolvedGenericItem<'db>> {
let mut maybe_env = Some(&mut *env);
while let Some(curr_env) = maybe_env {
if let Some(var) = curr_env.use_items.get(&item_name) {
curr_env.used_use_items.insert(item_name);
return Some(var.resolved_generic_item.clone());
}
maybe_env = curr_env.parent.as_deref_mut();
}
None
}
/// Computes the semantic model of an expression.
/// Note that this expr will always be "registered" in the arena, so it can be looked up in the
/// language server.
pub fn compute_expr_semantic<'db>(
ctx: &mut ComputationContext<'db, '_>,
syntax: &ast::Expr<'db>,
) -> ExprAndId<'db> {
let expr = maybe_compute_expr_semantic(ctx, syntax);
let expr = wrap_maybe_with_missing(ctx, expr, syntax.stable_ptr(ctx.db));
let id = ctx.arenas.exprs.alloc(expr.clone());
ExprAndId { expr, id }
}
/// Converts `Maybe<Expr>` to a possibly [missing](ExprMissing) [Expr].
fn wrap_maybe_with_missing<'db>(
ctx: &mut ComputationContext<'db, '_>,
expr: Maybe<Expr<'db>>,
stable_ptr: ast::ExprPtr<'db>,
) -> Expr<'db> {
expr.unwrap_or_else(|diag_added| {
Expr::Missing(ExprMissing {
ty: TypeId::missing(ctx.db, diag_added),
stable_ptr,
diag_added,
})
})
}
/// Computes the semantic model of an expression, or returns a SemanticDiagnosticKind on error.
pub fn maybe_compute_expr_semantic<'db>(
ctx: &mut ComputationContext<'db, '_>,
syntax: &ast::Expr<'db>,
) -> Maybe<Expr<'db>> {
let db = ctx.db;
// TODO(spapini): When Expr holds the syntax pointer, add it here as well.
match syntax {
ast::Expr::Path(path) => resolve_expr_path(ctx, path),
ast::Expr::Literal(literal_syntax) => {
Ok(Expr::Literal(literal_to_semantic(ctx, literal_syntax)?))
}
ast::Expr::ShortString(literal_syntax) => {
Ok(Expr::Literal(short_string_to_semantic(ctx, literal_syntax)?))
}
ast::Expr::String(literal_syntax) => {
Ok(Expr::StringLiteral(string_literal_to_semantic(ctx, literal_syntax)?))
}
ast::Expr::False(syntax) => Ok(false_literal_expr(ctx, syntax.stable_ptr(db).into())),
ast::Expr::True(syntax) => Ok(true_literal_expr(ctx, syntax.stable_ptr(db).into())),
ast::Expr::Parenthesized(paren_syntax) => {
maybe_compute_expr_semantic(ctx, &paren_syntax.expr(db))
}
ast::Expr::Unary(syntax) => compute_expr_unary_semantic(ctx, syntax),
ast::Expr::Binary(binary_op_syntax) => compute_expr_binary_semantic(ctx, binary_op_syntax),
ast::Expr::Tuple(tuple_syntax) => compute_expr_tuple_semantic(ctx, tuple_syntax),
ast::Expr::FunctionCall(call_syntax) => {
compute_expr_function_call_semantic(ctx, call_syntax)
}
ast::Expr::StructCtorCall(ctor_syntax) => struct_ctor_expr(ctx, ctor_syntax),
ast::Expr::Block(block_syntax) => compute_expr_block_semantic(ctx, block_syntax),
ast::Expr::Match(expr_match) => compute_expr_match_semantic(ctx, expr_match),
ast::Expr::If(expr_if) => compute_expr_if_semantic(ctx, expr_if),
ast::Expr::Loop(expr_loop) => compute_expr_loop_semantic(ctx, expr_loop),
ast::Expr::While(expr_while) => compute_expr_while_semantic(ctx, expr_while),
ast::Expr::ErrorPropagate(expr) => compute_expr_error_propagate_semantic(ctx, expr),
ast::Expr::InlineMacro(expr) => compute_expr_inline_macro_semantic(ctx, expr),
ast::Expr::Missing(_) | ast::Expr::FieldInitShorthand(_) => {
Err(ctx.diagnostics.report(syntax.stable_ptr(db), SemanticDiagnosticKind::Unsupported))
}
ast::Expr::Indexed(expr) => compute_expr_indexed_semantic(ctx, expr),
ast::Expr::FixedSizeArray(expr) => compute_expr_fixed_size_array_semantic(ctx, expr),
ast::Expr::For(expr) => compute_expr_for_semantic(ctx, expr),
ast::Expr::Closure(expr) => compute_expr_closure_semantic(ctx, expr, None),
ast::Expr::Underscore(expr) => {
Err(ctx.diagnostics.report(expr.stable_ptr(db), SemanticDiagnosticKind::Unsupported))
}
}
}
/// Expands an inline macro invocation and returns the generated code and related metadata.
fn expand_inline_macro<'db>(
ctx: &mut ComputationContext<'db, '_>,
syntax: &ast::ExprInlineMacro<'db>,
) -> Maybe<InlineMacroExpansion<'db>> {
let db = ctx.db;
let macro_path = syntax.path(db);
let crate_id = ctx.resolver.owning_crate_id;
// Skipping expanding an inline macro if it had a parser error.
if syntax.as_syntax_node().descendants(db).any(|node| node.kind(db).is_missing()) {
return Err(skip_diagnostic());
}
// We call the resolver with a new diagnostics, since the diagnostics should not be reported
// if the macro was found as a plugin.
let user_defined_macro = ctx.resolver.resolve_generic_path(
&mut SemanticDiagnostics::new(ctx.resolver.module_id),
¯o_path,
NotFoundItemType::Macro,
ResolutionContext::Statement(&mut ctx.environment),
);
if let Ok(ResolvedGenericItem::Macro(macro_declaration_id)) = user_defined_macro {
let macro_rules = ctx.db.macro_declaration_rules(macro_declaration_id)?;
let Some((rule, (captures, placeholder_to_rep_id))) = macro_rules.iter().find_map(|rule| {
is_macro_rule_match(ctx.db, rule, &syntax.arguments(db)).map(|res| (rule, res))
}) else {
return Err(ctx.diagnostics.report(
syntax.stable_ptr(ctx.db),
InlineMacroNoMatchingRule(macro_path.identifier(db)),
));
};
let mut matcher_ctx =
MatcherContext { captures, placeholder_to_rep_id, ..Default::default() };
let expanded_code = expand_macro_rule(ctx.db, rule, &mut matcher_ctx)?;
let macro_defsite_resolver_data =
ctx.db.macro_declaration_resolver_data(macro_declaration_id)?;
let callsite_module_id = ctx.resolver.data.module_id;
let parent_macro_call_data = ctx.resolver.macro_call_data.clone();
let info = MacroExpansionInfo {
mappings: expanded_code.code_mappings,
kind: MacroKind::UserDefined,
vars_to_expose: vec![],
};
ctx.resolver.macro_call_data = Some(Arc::new(ResolverMacroData {
defsite_module_id: macro_defsite_resolver_data.module_id,
callsite_module_id,
expansion_mappings: info.mappings.clone(),
parent_macro_call_data,
}));
Ok(InlineMacroExpansion {
content: expanded_code.text,
name: macro_path.identifier(db).to_string(db),
info,
})
} else if let Some(macro_plugin_id) = ctx
.resolver
.resolve_plugin_macro(¯o_path, ResolutionContext::Statement(&mut ctx.environment))
{
let macro_plugin = macro_plugin_id.long(ctx.db);
let result = macro_plugin.generate_code(
db,
syntax,
&MacroPluginMetadata {
cfg_set: &ctx.cfg_set,
declared_derives: ctx.db.declared_derives(crate_id),
allowed_features: &ctx.resolver.data.feature_config.allowed_features,
edition: ctx.resolver.settings.edition,
},
);
let mut diag_added = None;
for diagnostic in result.diagnostics {
diag_added = match diagnostic.inner_span {
None => Some(
ctx.diagnostics.report(diagnostic.stable_ptr, PluginDiagnostic(diagnostic)),
),
Some((offset, width)) => Some(ctx.diagnostics.report_with_inner_span(
diagnostic.stable_ptr,
(offset, width),
PluginDiagnostic(diagnostic),
)),
}
}
let Some(code) = result.code else {
return Err(diag_added.unwrap_or_else(|| {
ctx.diagnostics.report(
syntax.stable_ptr(ctx.db),
InlineMacroNotFound(macro_path.identifier(db)),
)
}));
};
Ok(InlineMacroExpansion {
content: code.content.into(),
name: code.name.to_string(),
info: MacroExpansionInfo {
mappings: code.code_mappings.into(),
kind: if code.is_unhygienic { MacroKind::Unhygienic } else { MacroKind::Plugin },
vars_to_expose: vec![],
},
})
} else {
let macro_name = syntax.path(db).as_syntax_node().get_text_without_trivia(db);
Err(ctx.diagnostics.report(syntax.stable_ptr(db), InlineMacroNotFound(macro_name)))
}
}
/// Expands and computes the semantic model of an inline macro used in expression position.
fn compute_expr_inline_macro_semantic<'db>(
ctx: &mut ComputationContext<'db, '_>,
syntax: &ast::ExprInlineMacro<'db>,
) -> Maybe<Expr<'db>> {
let prev_macro_call_data = ctx.resolver.macro_call_data.clone();
let InlineMacroExpansion { content, name, info } = expand_inline_macro(ctx, syntax)?;
let new_file_id = FileLongId::Virtual(VirtualFile {
parent: Some(syntax.stable_ptr(ctx.db).untyped().span_in_file(ctx.db)),
name: SmolStrId::from(ctx.db, name),
content: SmolStrId::from(ctx.db, content),
code_mappings: info.mappings.clone(),
kind: FileKind::Expr,
original_item_removed: true,
})
.intern(ctx.db);
ctx.resolver.files.push(new_file_id);
let expr_syntax = ctx.db.file_expr_syntax(new_file_id)?;
let parser_diagnostics = ctx.db.file_syntax_diagnostics(new_file_id);
if let Err(diag_added) = parser_diagnostics.check_error_free() {
for diag in parser_diagnostics.get_diagnostics_without_duplicates(ctx.db) {
ctx.diagnostics.report(
syntax.stable_ptr(ctx.db),
SemanticDiagnosticKind::MacroGeneratedCodeParserDiagnostic(diag),
);
}
return Err(diag_added);
}
let expr = ctx.run_in_macro_subscope(|ctx| compute_expr_semantic(ctx, &expr_syntax), info);
ctx.resolver.macro_call_data = prev_macro_call_data;
Ok(expr.expr)
}
/// Computes the semantic model of a tail expression, handling inline macros recursively and
/// ensuring the correct tail expression is extracted from the resulting statements.
fn compute_tail_semantic<'db>(
ctx: &mut ComputationContext<'db, '_>,
tail: &ast::StatementExpr<'db>,
statements_ids: &mut Vec<StatementId>,
) -> ExprAndId<'db> {
// Push the statement's attributes into the context, restored after the computation is resolved.
let feature_restore = ctx.add_features_from_statement(tail);
let db = ctx.db;
let expr = tail.expr(db);
let res = match &expr {
ast::Expr::InlineMacro(inline_macro_syntax) => {
match expand_macro_for_statement(ctx, inline_macro_syntax, true, statements_ids) {
Ok(Some(expr_and_id)) => expr_and_id,
Ok(None) => unreachable!("Tail expression should not be None"),
Err(diag_added) => {
let expr = Expr::Missing(ExprMissing {
ty: TypeId::missing(db, diag_added),
stable_ptr: expr.stable_ptr(db),
diag_added,
});
ExprAndId { id: ctx.arenas.exprs.alloc(expr.clone()), expr }
}
}
}
_ => compute_expr_semantic(ctx, &expr),
};
// Pop the statement's attributes from the context.
ctx.restore_features(feature_restore);
res
}
/// Expands an inline macro used in statement position, computes its semantic model, and extends
/// `statements` with it.
fn expand_macro_for_statement<'db>(
ctx: &mut ComputationContext<'db, '_>,
syntax: &ast::ExprInlineMacro<'db>,
is_tail: bool,
statements_ids: &mut Vec<StatementId>,
) -> Maybe<Option<ExprAndId<'db>>> {
let prev_macro_call_data = ctx.resolver.macro_call_data.clone();
let InlineMacroExpansion { content, name, info } = expand_inline_macro(ctx, syntax)?;
let new_file_id = FileLongId::Virtual(VirtualFile {
parent: Some(syntax.stable_ptr(ctx.db).untyped().span_in_file(ctx.db)),
name: SmolStrId::from(ctx.db, name),
content: SmolStrId::from_arcstr(ctx.db, &content),
code_mappings: info.mappings.clone(),
kind: FileKind::StatementList,
original_item_removed: true,
})
.intern(ctx.db);
ctx.resolver.files.push(new_file_id);
let parser_diagnostics = ctx.db.file_syntax_diagnostics(new_file_id);
if let Err(diag_added) = parser_diagnostics.check_error_free() {
for diag in parser_diagnostics.get_diagnostics_without_duplicates(ctx.db) {
ctx.diagnostics.report(
syntax.stable_ptr(ctx.db),
SemanticDiagnosticKind::MacroGeneratedCodeParserDiagnostic(diag),
);
}
return Err(diag_added);
}
let statement_list = ctx.db.file_statement_list_syntax(new_file_id)?;
let (parsed_statements, tail) = statements_and_tail(ctx.db, statement_list);
let result = ctx.run_in_macro_subscope(
|ctx| {
compute_statements_semantic_and_extend(ctx, parsed_statements, statements_ids);
if is_tail {
if let Some(tail_expr) = tail {
Ok(Some(compute_tail_semantic(ctx, &tail_expr, statements_ids)))
} else {
Err(ctx.diagnostics.report_after(syntax.stable_ptr(ctx.db), MissingSemicolon))
}
} else {
if let Some(tail_expr) = tail {
let expr = compute_expr_semantic(ctx, &tail_expr.expr(ctx.db));
statements_ids.push(ctx.arenas.statements.alloc(semantic::Statement::Expr(
semantic::StatementExpr {
expr: expr.id,
stable_ptr: tail_expr.stable_ptr(ctx.db).into(),
},
)));
}
Ok(None)
}
},
info,
);
ctx.resolver.macro_call_data = prev_macro_call_data;
result
}
fn compute_expr_unary_semantic<'db>(