slang_solidity 1.3.2

A modular set of compiler APIs empowering the next generation of Solidity code analysis and developer tooling. Written in Rust and distributed in multiple languages.
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
use std::rc::Rc;

use semver::Version;

use crate::backend::binder::{Binder, Definition, FileScope, ParametersScope, Scope, ScopeId};
use crate::backend::ir::ir2_flat_contracts::visitor::Visitor;
use crate::backend::ir::ir2_flat_contracts::{self as input_ir};
use crate::backend::semantic::SemanticAnalysis;
use crate::compilation::File;
use crate::cst::{NodeId, TerminalNode};
use crate::utils::versions::VERSION_0_5_0;

/// In this pass all definitions are collected with their naming identifiers.
/// Also lexical (and other kinds of) scopes are identified and linked together,
/// and definitions are registered into them for later lookup. The pass
/// instantiates a `Binder` object which will store all this information as well
/// as references and typing information for the nodes, to be resolved in later
/// passes.
pub fn run(semantic_analysis: &mut SemanticAnalysis) {
    let mut pass = Pass::new(
        semantic_analysis.language_version().clone(),
        &mut semantic_analysis.binder,
    );
    for semantic_file in semantic_analysis.files.values() {
        pass.visit_file(semantic_file.file(), semantic_file.ir_root());
    }
}

struct ScopeFrame {
    // Scope associated with the node that created the stack frame. This is
    // solely used for integrity validation when popping the current frame.
    structural_scope_id: ScopeId,
    // Scope to use when resolving a symbol.
    lexical_scope_id: ScopeId,
}

struct Pass<'a> {
    language_version: Version,
    current_file: Option<Rc<File>>, // needed to resolve imports on the file
    scope_stack: Vec<ScopeFrame>,
    binder: &'a mut Binder,
}

impl<'a> Pass<'a> {
    fn new(language_version: Version, binder: &'a mut Binder) -> Self {
        Self {
            language_version,
            current_file: None,
            scope_stack: Vec::new(),
            binder,
        }
    }

    fn visit_file(&mut self, file: &Rc<File>, source_unit: &input_ir::SourceUnit) {
        assert!(self.current_file.is_none());

        self.current_file = Some(Rc::clone(file));
        input_ir::visitor::accept_source_unit(source_unit, self);
        self.current_file = None;

        assert!(self.scope_stack.is_empty());
    }

    fn enter_scope(&mut self, scope: Scope) -> ScopeId {
        let scope_id = self.binder.insert_scope(scope);
        self.scope_stack.push(ScopeFrame {
            structural_scope_id: scope_id,
            lexical_scope_id: scope_id,
        });
        scope_id
    }

    fn replace_scope(&mut self, scope: Scope) -> ScopeId {
        let Some(ScopeFrame {
            structural_scope_id,
            ..
        }) = self.scope_stack.pop()
        else {
            unreachable!("scope stack cannot be empty");
        };

        let scope_id = self.binder.insert_scope(scope);
        self.scope_stack.push(ScopeFrame {
            structural_scope_id,
            lexical_scope_id: scope_id,
        });
        scope_id
    }

    fn enter_scope_for_node_id(&mut self, node_id: NodeId) {
        let scope_id = self.binder.scope_id_for_node_id(node_id).unwrap();
        self.scope_stack.push(ScopeFrame {
            structural_scope_id: scope_id,
            lexical_scope_id: scope_id,
        });
    }

    fn leave_scope_for_node_id(&mut self, node_id: NodeId) {
        let Some(ScopeFrame {
            structural_scope_id,
            ..
        }) = self.scope_stack.pop()
        else {
            unreachable!("attempt to pop an empty scope stack");
        };
        assert_eq!(
            structural_scope_id,
            self.binder.scope_id_for_node_id(node_id).unwrap()
        );
    }

    fn current_scope_id(&self) -> ScopeId {
        let Some(ScopeFrame {
            lexical_scope_id, ..
        }) = self.scope_stack.last()
        else {
            unreachable!("empty scope stack");
        };
        *lexical_scope_id
    }

    fn current_scope(&mut self) -> &mut Scope {
        let scope_id = self.current_scope_id();
        self.binder.get_scope_mut(scope_id)
    }

    fn current_file_scope(&mut self) -> &mut FileScope {
        let Scope::File(file_scope) = self.current_scope() else {
            unreachable!("current scope is not a file scope");
        };
        file_scope
    }

    fn insert_definition_in_current_scope(&mut self, definition: Definition) {
        self.binder
            .insert_definition_in_scope(definition, self.current_scope_id());
    }

    fn resolve_import_path(&self, import_path: &Rc<TerminalNode>) -> Option<String> {
        let import_path_node_id = import_path.id();
        let current_file = self
            .current_file
            .as_ref()
            .expect("import directive must be visited in the context of a current file");
        current_file
            .resolved_import_by_node_id(import_path_node_id)
            .map(|file_id| file_id.to_string())

        // TODO(validation): emit an error/warning if the file cannot be resolved
    }

    // Collects *all* the sequential parameters making and registering
    // definitions for named ones and return the constructed parameters scope ID
    // to link with the enclosing function definition
    fn collect_parameters(&mut self, parameters: &input_ir::Parameters) -> ScopeId {
        let mut scope = ParametersScope::new();
        for parameter in parameters {
            scope.add_parameter(parameter.name.as_ref(), parameter.node_id);
            if parameter.name.is_some() {
                let definition = Definition::new_parameter(parameter);
                self.binder.insert_definition_no_scope(definition);
            }
        }
        self.binder.insert_scope(Scope::Parameters(scope))
    }

    // This is used to collect only named parameters and insert their
    // definitions into an existing scope. Used mostly for return parameters,
    // where position and types are not used for binding.
    fn collect_named_parameters_into_scope(
        &mut self,
        parameters: &input_ir::Parameters,
        scope_id: ScopeId,
    ) {
        for parameter in parameters {
            if parameter.name.is_some() {
                let definition = Definition::new_parameter(parameter);
                self.binder.insert_definition_in_scope(definition, scope_id);
            }
        }
    }

    fn register_constructor_parameters(&mut self, constructor_parameters_scope_id: ScopeId) {
        let current_scope_node_id = self.current_scope().node_id();
        let Definition::Contract(contract_definition) =
            self.binder.get_definition_mut(current_scope_node_id)
        else {
            unreachable!("the current scope is not a contract");
        };
        // TODO(validation): there should be a single constructor, so the
        // current value should be None
        contract_definition.constructor_parameters_scope_id = Some(constructor_parameters_scope_id);
    }
}

impl Visitor for Pass<'_> {
    fn enter_source_unit(&mut self, node: &input_ir::SourceUnit) -> bool {
        let Some(current_file) = &self.current_file else {
            unreachable!("visiting SourceUnit without a current file being set");
        };
        let scope = Scope::new_file(node.node_id, current_file.id());
        self.enter_scope(scope);

        true
    }

    fn leave_source_unit(&mut self, node: &input_ir::SourceUnit) {
        self.leave_scope_for_node_id(node.node_id);
    }

    fn enter_contract_definition(&mut self, node: &input_ir::ContractDefinition) -> bool {
        let definition = Definition::new_contract(node);
        self.insert_definition_in_current_scope(definition);

        let scope = Scope::new_contract(node.node_id, self.current_scope_id());
        self.enter_scope(scope);

        true
    }

    fn leave_contract_definition(&mut self, node: &input_ir::ContractDefinition) {
        self.leave_scope_for_node_id(node.node_id);
    }

    fn enter_library_definition(&mut self, node: &input_ir::LibraryDefinition) -> bool {
        let definition = Definition::new_library(node);
        self.insert_definition_in_current_scope(definition);

        let scope = Scope::new_contract(node.node_id, self.current_scope_id());
        self.enter_scope(scope);

        true
    }

    fn leave_library_definition(&mut self, node: &input_ir::LibraryDefinition) {
        self.leave_scope_for_node_id(node.node_id);
    }

    fn enter_interface_definition(&mut self, node: &input_ir::InterfaceDefinition) -> bool {
        let definition = Definition::new_interface(node);
        self.insert_definition_in_current_scope(definition);

        let scope = Scope::new_contract(node.node_id, self.current_scope_id());
        self.enter_scope(scope);

        true
    }

    fn leave_interface_definition(&mut self, node: &input_ir::InterfaceDefinition) {
        self.leave_scope_for_node_id(node.node_id);
    }

    fn enter_path_import(&mut self, node: &input_ir::PathImport) -> bool {
        let imported_file_id = self.resolve_import_path(&node.path);

        if node.alias.is_some() {
            let definition = Definition::new_import(node, imported_file_id);
            self.insert_definition_in_current_scope(definition);
        } else if let Some(imported_file_id) = imported_file_id {
            self.current_file_scope()
                .add_imported_file(imported_file_id);
        }

        false
    }

    fn enter_import_deconstruction(&mut self, node: &input_ir::ImportDeconstruction) -> bool {
        let imported_file_id = self.resolve_import_path(&node.path);

        for symbol in &node.symbols {
            let definition = Definition::new_imported_symbol(
                symbol,
                symbol.name.unparse(),
                imported_file_id.clone(),
            );
            self.insert_definition_in_current_scope(definition);
        }

        false
    }

    fn enter_function_definition(&mut self, node: &input_ir::FunctionDefinition) -> bool {
        match node.kind {
            input_ir::FunctionKind::Regular
            | input_ir::FunctionKind::Constructor
            | input_ir::FunctionKind::Fallback
            | input_ir::FunctionKind::Receive
            | input_ir::FunctionKind::Unnamed => {
                let parameters_scope_id = self.collect_parameters(&node.parameters);

                if let Some(name) = &node.name {
                    let visibility = (&node.visibility).into();
                    let definition =
                        Definition::new_function(node, parameters_scope_id, visibility);

                    let current_scope_node_id = self.current_scope().node_id();
                    let enclosing_definition =
                        self.binder.find_definition_by_id(current_scope_node_id);
                    let enclosing_contract_name =
                        if let Some(enclosing_definition) = enclosing_definition {
                            if matches!(enclosing_definition, Definition::Contract(_)) {
                                Some(enclosing_definition.identifier().unparse())
                            } else {
                                None
                            }
                        } else {
                            None
                        };

                    if enclosing_contract_name
                        .is_some_and(|contract_name| contract_name == name.unparse())
                    {
                        // TODO(validation): for Solidity >= 0.5.0 there cannot be a
                        // function with the same name as the enclosing contract. In any
                        // case, if the names match we don't register the definition in
                        // the current scope.
                        self.binder.insert_definition_no_scope(definition);

                        // For Solidity < 0.5.0, a function with the same name as the
                        // enclosing contract is a constructor, and we need to register the
                        // constructor parameters scope.
                        if self.language_version < VERSION_0_5_0 {
                            self.register_constructor_parameters(parameters_scope_id);
                        }
                    } else {
                        self.insert_definition_in_current_scope(definition);
                    }
                } else if matches!(node.kind, input_ir::FunctionKind::Constructor) {
                    // Register the constructor to resolve named parameters when
                    // constructing this contract
                    self.register_constructor_parameters(parameters_scope_id);
                }

                let function_scope =
                    Scope::new_function(node.node_id, self.current_scope_id(), parameters_scope_id);
                let function_scope_id = self.enter_scope(function_scope);

                if let Some(returns) = &node.returns {
                    self.collect_named_parameters_into_scope(returns, function_scope_id);
                }
            }

            input_ir::FunctionKind::Modifier => {
                let definition = Definition::new_modifier(node);
                self.insert_definition_in_current_scope(definition);

                let modifier_scope = Scope::new_modifier(node.node_id, self.current_scope_id());
                let modifier_scope_id = self.enter_scope(modifier_scope);
                self.collect_named_parameters_into_scope(&node.parameters, modifier_scope_id);
            }
        }
        true
    }

    fn leave_function_definition(&mut self, node: &input_ir::FunctionDefinition) {
        self.leave_scope_for_node_id(node.node_id);
    }

    fn enter_enum_definition(&mut self, node: &input_ir::EnumDefinition) -> bool {
        let definition = Definition::new_enum(node);
        self.insert_definition_in_current_scope(definition);

        let enum_scope = Scope::new_enum(node.node_id);
        let enum_scope_id = self.binder.insert_scope(enum_scope);
        for member in &node.members {
            let definition = Definition::new_enum_member(member);
            self.binder
                .insert_definition_in_scope(definition, enum_scope_id);
        }

        false
    }

    fn enter_struct_definition(&mut self, node: &input_ir::StructDefinition) -> bool {
        let definition = Definition::new_struct(node);
        self.insert_definition_in_current_scope(definition);

        let struct_scope = Scope::new_struct(node.node_id);
        let struct_scope_id = self.binder.insert_scope(struct_scope);
        for member in &node.members {
            let definition = Definition::new_struct_member(member);
            self.binder
                .insert_definition_in_scope(definition, struct_scope_id);
        }

        true
    }

    fn enter_error_definition(&mut self, node: &input_ir::ErrorDefinition) -> bool {
        let parameters_scope_id = self.collect_parameters(&node.parameters);
        let definition = Definition::new_error(node, parameters_scope_id);
        self.insert_definition_in_current_scope(definition);

        false
    }

    fn enter_event_definition(&mut self, node: &input_ir::EventDefinition) -> bool {
        let parameters_scope_id = self.collect_parameters(&node.parameters);
        let definition = Definition::new_event(node, parameters_scope_id);
        self.insert_definition_in_current_scope(definition);

        false
    }

    fn enter_state_variable_definition(
        &mut self,
        node: &input_ir::StateVariableDefinition,
    ) -> bool {
        let visibility = (&node.visibility).into();
        let definition = Definition::new_state_variable(node, visibility);
        self.insert_definition_in_current_scope(definition);

        // there may be more definitions in the type of the state variable (eg.
        // key/value names in mappings)
        true
    }

    fn enter_constant_definition(&mut self, node: &input_ir::ConstantDefinition) -> bool {
        let definition = Definition::new_constant(node);
        self.insert_definition_in_current_scope(definition);

        false
    }

    fn enter_user_defined_value_type_definition(
        &mut self,
        node: &input_ir::UserDefinedValueTypeDefinition,
    ) -> bool {
        let definition = Definition::new_user_defined_value_type(node);
        self.insert_definition_in_current_scope(definition);

        false
    }

    fn leave_variable_declaration_statement(
        &mut self,
        node: &input_ir::VariableDeclarationStatement,
    ) {
        if self.language_version >= VERSION_0_5_0 {
            // In Solidity >= 0.5.0 this definition should only be available for
            // statements after this one. So we open a new scope that replaces
            // but is linked to the current one
            let scope = Scope::new_block(node.node_id, self.current_scope_id());
            self.replace_scope(scope);
        }

        let definition = Definition::new_variable(node);
        self.insert_definition_in_current_scope(definition);
    }

    fn enter_block(&mut self, node: &input_ir::Block) -> bool {
        if self.language_version >= VERSION_0_5_0 {
            let scope = Scope::new_block(node.node_id, self.current_scope_id());
            self.enter_scope(scope);
        }
        true
    }

    fn leave_block(&mut self, node: &input_ir::Block) {
        if self.language_version >= VERSION_0_5_0 {
            self.leave_scope_for_node_id(node.node_id);
        }
    }

    fn enter_for_statement(&mut self, node: &input_ir::ForStatement) -> bool {
        if self.language_version >= VERSION_0_5_0 {
            // For Solidity >= 0.5.0 open a new block here to hold declarations
            // in the initialization clause.
            let scope = Scope::new_block(node.node_id, self.current_scope_id());
            self.enter_scope(scope);
        }
        true
    }

    fn leave_for_statement(&mut self, node: &input_ir::ForStatement) {
        if self.language_version >= VERSION_0_5_0 {
            self.leave_scope_for_node_id(node.node_id);
        }
    }

    fn leave_try_statement(&mut self, node: &input_ir::TryStatement) {
        if self.language_version < VERSION_0_5_0 {
            return;
        }
        if let Some(returns) = &node.returns {
            // For Solidity >= 0.5.0, collect the parameters in the returns
            // declaration of the try statement and make them available in the
            // body block.
            let body_scope_id = self.binder.scope_id_for_node_id(node.body.node_id).unwrap();
            self.collect_named_parameters_into_scope(returns, body_scope_id);
        }
    }

    fn leave_catch_clause(&mut self, node: &input_ir::CatchClause) {
        if let Some(error) = &node.error {
            // For Solidity >= 0.5.0, collect the parameters in the catch
            // declaration and make them available in the body block.
            let body_scope_id = self.binder.scope_id_for_node_id(node.body.node_id).unwrap();
            self.collect_named_parameters_into_scope(&error.parameters, body_scope_id);
        }
    }

    fn enter_mapping_type(&mut self, node: &input_ir::MappingType) -> bool {
        if node.key_type.name.is_some() {
            let definition = Definition::new_type_parameter(&node.key_type);
            self.binder.insert_definition_no_scope(definition);
        }
        if node.value_type.name.is_some() {
            let definition = Definition::new_type_parameter(&node.value_type);
            self.binder.insert_definition_no_scope(definition);
        }

        true
    }

    fn enter_function_type(&mut self, node: &input_ir::FunctionType) -> bool {
        for parameter in &node.parameters {
            if parameter.name.is_some() {
                let definition = Definition::new_type_parameter(parameter);
                self.binder.insert_definition_no_scope(definition);
            }
        }
        if let Some(returns) = &node.returns {
            for parameter in returns {
                if parameter.name.is_some() {
                    let definition = Definition::new_type_parameter(parameter);
                    self.binder.insert_definition_no_scope(definition);
                }
            }
        }

        false
    }

    fn enter_yul_block(&mut self, node: &input_ir::YulBlock) -> bool {
        let scope = Scope::new_yul_block(node.node_id, self.current_scope_id());
        self.enter_scope(scope);

        true
    }

    fn leave_yul_block(&mut self, node: &input_ir::YulBlock) {
        self.leave_scope_for_node_id(node.node_id);
    }

    fn enter_yul_function_definition(&mut self, node: &input_ir::YulFunctionDefinition) -> bool {
        let definition = Definition::new_yul_function(node);
        self.insert_definition_in_current_scope(definition);

        let scope = Scope::new_yul_function(node.node_id, self.current_scope_id());
        let scope_id = self.enter_scope(scope);

        for parameter in &node.parameters {
            let definition = Definition::new_yul_parameter(parameter);
            self.binder.insert_definition_in_scope(definition, scope_id);
        }
        if let Some(returns) = &node.returns {
            for parameter in returns {
                let definition = Definition::new_yul_variable(parameter);
                self.binder.insert_definition_in_scope(definition, scope_id);
            }
        }

        true
    }

    fn leave_yul_function_definition(&mut self, node: &input_ir::YulFunctionDefinition) {
        self.leave_scope_for_node_id(node.node_id);
    }

    fn enter_yul_label(&mut self, node: &input_ir::YulLabel) -> bool {
        let definition = Definition::new_yul_label(node);
        self.insert_definition_in_current_scope(definition);

        false
    }

    fn enter_yul_variable_declaration_statement(
        &mut self,
        node: &input_ir::YulVariableDeclarationStatement,
    ) -> bool {
        for variable in &node.variables {
            let definition = Definition::new_yul_variable(variable);
            self.insert_definition_in_current_scope(definition);
        }
        // TODO: we maybe want to enter a new scope here, but that should be
        // only relevant for validation (ie. to avoid referencing a variable
        // before declaring it). If we do that, we need to take special care of
        // where we insert label and function definitions, since those are
        // hoisted in the block.

        false
    }

    fn enter_yul_for_statement(&mut self, node: &input_ir::YulForStatement) -> bool {
        // Visit the initialization block first
        input_ir::visitor::accept_yul_block(&node.initialization, self);

        // Visit the rest of the children, but in the scope of the
        // initialization block such that iterator and body blocks link to it
        self.enter_scope_for_node_id(node.initialization.node_id);
        input_ir::visitor::accept_yul_expression(&node.condition, self);
        input_ir::visitor::accept_yul_block(&node.iterator, self);
        input_ir::visitor::accept_yul_block(&node.body, self);
        self.leave_scope_for_node_id(node.initialization.node_id);

        // We already visited our children
        false
    }
}