-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathcontext.rs
549 lines (483 loc) · 16.3 KB
/
context.rs
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
use crate::namespace::items::{
Class, ContractId, DiagnosticSink, EventId, FunctionId, FunctionSigId, Item, TraitId,
};
use crate::namespace::types::{Generic, SelfDecl, Struct, Type};
use crate::AnalyzerDb;
use crate::{
builtins::{ContractTypeMethod, GlobalFunction, Intrinsic, ValueMethod},
namespace::scopes::BlockScopeType,
};
use crate::{
errors::{self, CannotMove, IncompleteItem, TypeError},
namespace::items::ModuleId,
};
use fe_common::diagnostics::Diagnostic;
pub use fe_common::diagnostics::Label;
use fe_common::Span;
use fe_parser::ast;
use fe_parser::node::{Node, NodeId};
use indexmap::{IndexMap, IndexSet};
use num_bigint::BigInt;
use smol_str::SmolStr;
use std::fmt::{self, Debug, Display};
use std::hash::Hash;
use std::marker::PhantomData;
use std::rc::Rc;
use std::{cell::RefCell, collections::HashMap};
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct Analysis<T> {
pub value: T,
pub diagnostics: Rc<[Diagnostic]>,
}
impl<T> Analysis<T> {
pub fn new(value: T, diagnostics: Rc<[Diagnostic]>) -> Self {
Self { value, diagnostics }
}
pub fn sink_diagnostics(&self, sink: &mut impl DiagnosticSink) {
self.diagnostics.iter().for_each(|diag| sink.push(diag))
}
}
pub trait AnalyzerContext {
fn resolve_name(&self, name: &str, span: Span) -> Result<Option<NamedThing>, IncompleteItem>;
fn resolve_path(&self, path: &ast::Path, span: Span) -> Option<NamedThing>;
fn add_diagnostic(&self, diag: Diagnostic);
fn db(&self) -> &dyn AnalyzerDb;
fn error(&mut self, message: &str, label_span: Span, label: &str) -> DiagnosticVoucher {
self.register_diag(errors::error(message, label_span, label))
}
/// Attribute contextual information to an expression node.
///
/// # Panics
///
/// Panics if an entry already exists for the node id.
fn add_expression(&self, node: &Node<ast::Expr>, attributes: ExpressionAttributes);
/// Update the expression attributes.
///
/// # Panics
///
/// Panics if an entry does not already exist for the node id.
fn update_expression(&self, node: &Node<ast::Expr>, attributes: ExpressionAttributes);
/// Returns a type of an expression.
///
/// # Panics
///
/// Panics if type analysis is not performed for an `expr`.
fn expr_typ(&self, expr: &Node<ast::Expr>) -> Type;
/// Add evaluated constant value in a constant declaration to the context.
fn add_constant(&self, name: &Node<ast::SmolStr>, expr: &Node<ast::Expr>, value: Constant);
/// Returns constant value from variable name.
fn constant_value_by_name(
&self,
name: &ast::SmolStr,
span: Span,
) -> Result<Option<Constant>, IncompleteItem>;
/// Returns an item enclosing current context.
///
/// # Example
///
/// ```fe
/// contract Foo:
/// fn foo():
/// if ...:
/// ...
/// else:
/// ...
/// ```
/// If the context is in `then` block, then this function returns
/// `Item::Function(..)`.
fn parent(&self) -> Item;
/// Returns the module enclosing current context.
fn module(&self) -> ModuleId;
/// Returns a function id that encloses a context.
///
/// # Panics
///
/// Panics if a context is not in a function. Use [`Self::is_in_function`]
/// to determine whether a context is in a function.
fn parent_function(&self) -> FunctionId;
/// Returns a non-function item that encloses a context.
///
/// # Example
///
/// ```fe
/// contract Foo:
/// fn foo():
/// if ...:
/// ...
/// else:
/// ...
/// ```
/// If the context is in `then` block, then this function returns
/// `Item::Type(TypeDef::Contract(..))`.
fn root_item(&self) -> Item {
let mut item = self.parent();
while let Item::Function(func_id) = item {
item = func_id.parent(self.db());
}
item
}
/// # Panics
///
/// Panics if a context is not in a function. Use [`Self::is_in_function`]
/// to determine whether a context is in a function.
fn add_call(&self, node: &Node<ast::Expr>, call_type: CallType);
/// Store string literal to the current context.
///
/// # Panics
///
/// Panics if a context is not in a function. Use [`Self::is_in_function`]
/// to determine whether a context is in a function.
fn add_string(&self, str_lit: SmolStr);
/// Returns `true` if the context is in function scope.
fn is_in_function(&self) -> bool;
/// Returns `true` if the scope or any of its parents is of the given type.
fn inherits_type(&self, typ: BlockScopeType) -> bool;
/// Returns the `Context` type, if it is defined.
fn get_context_type(&self) -> Option<Struct>;
fn type_error(
&self,
message: &str,
span: Span,
expected: &dyn Display,
actual: &dyn Display,
) -> DiagnosticVoucher {
self.register_diag(errors::type_error(message, span, expected, actual))
}
fn not_yet_implemented(&self, feature: &str, span: Span) -> DiagnosticVoucher {
self.register_diag(errors::not_yet_implemented(feature, span))
}
fn fancy_error(
&self,
message: &str,
labels: Vec<Label>,
notes: Vec<String>,
) -> DiagnosticVoucher {
self.register_diag(errors::fancy_error(message, labels, notes))
}
fn duplicate_name_error(
&self,
message: &str,
name: &str,
original: Span,
duplicate: Span,
) -> DiagnosticVoucher {
self.register_diag(errors::duplicate_name_error(
message, name, original, duplicate,
))
}
fn name_conflict_error(
&self,
name_kind: &str, // Eg "function parameter" or "variable name"
name: &str,
original: &NamedThing,
original_span: Option<Span>,
duplicate_span: Span,
) -> DiagnosticVoucher {
self.register_diag(errors::name_conflict_error(
name_kind,
name,
original,
original_span,
duplicate_span,
))
}
fn register_diag(&self, diag: Diagnostic) -> DiagnosticVoucher {
self.add_diagnostic(diag);
DiagnosticVoucher(PhantomData::default())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NamedThing {
Item(Item),
SelfValue {
/// Function `self` parameter.
decl: Option<SelfDecl>,
/// The function's parent, if any. If `None`, `self` has been
/// used in a module-level function.
class: Option<Class>,
span: Option<Span>,
},
// SelfType // when/if we add a `Self` type keyword
Variable {
name: String,
typ: Result<Type, TypeError>,
is_const: bool,
span: Span,
},
}
impl NamedThing {
pub fn name_span(&self, db: &dyn AnalyzerDb) -> Option<Span> {
match self {
NamedThing::Item(item) => item.name_span(db),
NamedThing::SelfValue { span, .. } => *span,
NamedThing::Variable { span, .. } => Some(*span),
}
}
pub fn is_builtin(&self) -> bool {
match self {
NamedThing::Item(item) => item.is_builtin(),
NamedThing::Variable { .. } | NamedThing::SelfValue { .. } => false,
}
}
pub fn item_kind_display_name(&self) -> &str {
match self {
NamedThing::Item(item) => item.item_kind_display_name(),
NamedThing::Variable { .. } => "variable",
NamedThing::SelfValue { .. } => "value",
}
}
}
/// This should only be created by [`AnalyzerContext`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DiagnosticVoucher(PhantomData<()>);
impl DiagnosticVoucher {
pub fn assume_the_parser_handled_it() -> Self {
Self(PhantomData::default())
}
}
#[derive(Default)]
pub struct TempContext {
pub diagnostics: RefCell<Vec<Diagnostic>>,
}
impl AnalyzerContext for TempContext {
fn db(&self) -> &dyn AnalyzerDb {
panic!("TempContext has no analyzer db")
}
fn resolve_name(&self, _name: &str, _span: Span) -> Result<Option<NamedThing>, IncompleteItem> {
panic!("TempContext can't resolve names")
}
fn resolve_path(&self, _path: &ast::Path, _span: Span) -> Option<NamedThing> {
panic!("TempContext can't resolve paths")
}
fn add_expression(&self, _node: &Node<ast::Expr>, _attributes: ExpressionAttributes) {
panic!("TempContext can't store expression")
}
fn update_expression(&self, _node: &Node<ast::Expr>, _attributes: ExpressionAttributes) {
panic!("TempContext can't update expression");
}
fn expr_typ(&self, _expr: &Node<ast::Expr>) -> Type {
panic!("TempContext can't return expression type")
}
fn add_constant(&self, _name: &Node<ast::SmolStr>, _expr: &Node<ast::Expr>, _value: Constant) {
panic!("TempContext can't store constant")
}
fn constant_value_by_name(
&self,
_name: &ast::SmolStr,
_span: Span,
) -> Result<Option<Constant>, IncompleteItem> {
Ok(None)
}
fn parent(&self) -> Item {
panic!("TempContext has no root item")
}
fn module(&self) -> ModuleId {
panic!("TempContext has no module")
}
fn parent_function(&self) -> FunctionId {
panic!("TempContext has no parent function")
}
fn add_call(&self, _node: &Node<ast::Expr>, _call_type: CallType) {
panic!("TempContext can't add call");
}
fn add_string(&self, _str_lit: SmolStr) {
panic!("TempContext can't store string literal")
}
fn is_in_function(&self) -> bool {
false
}
fn inherits_type(&self, _typ: BlockScopeType) -> bool {
false
}
fn add_diagnostic(&self, diag: Diagnostic) {
self.diagnostics.borrow_mut().push(diag)
}
fn get_context_type(&self) -> Option<Struct> {
panic!("TempContext can't resolve Context")
}
}
/// Indicates where an expression is stored.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Location {
/// A storage value may not have a nonce known at compile time, so it is
/// optional.
Storage {
nonce: Option<usize>,
},
Memory,
Value,
}
impl Location {
/// The expected location of a value with the given type when being
/// assigned, returned, or passed.
pub fn assign_location(typ: &Type) -> Self {
match typ {
Type::Base(_) | Type::Contract(_) => Location::Value,
// For now assume that generics can only ever refer to structs
Type::Array(_)
| Type::Tuple(_)
| Type::String(_)
| Type::Struct(_)
| Type::Generic(_) => Location::Memory,
other => panic!("Type {other} can not be assigned, returned or passed"),
}
}
}
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct FunctionBody {
pub expressions: IndexMap<NodeId, ExpressionAttributes>,
pub emits: IndexMap<NodeId, EventId>,
pub string_literals: IndexSet<SmolStr>, // for yulgen
// Map lhs of variable declaration to type.
pub var_types: IndexMap<NodeId, Type>,
pub calls: IndexMap<NodeId, CallType>,
pub spans: HashMap<NodeId, Span>,
}
/// Contains contextual information relating to an expression AST node.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExpressionAttributes {
pub typ: Type,
pub location: Location,
pub move_location: Option<Location>,
// Evaluated constant value of const local definition.
pub const_value: Option<Constant>,
}
impl ExpressionAttributes {
pub fn new(typ: Type, location: Location) -> Self {
Self {
typ,
location,
move_location: None,
const_value: None,
}
}
/// Adds a move to memory.
pub fn into_cloned(mut self) -> Self {
self.move_location = Some(Location::Memory);
self
}
/// Adds a move to value, if it is in storage or memory.
pub fn into_loaded(mut self) -> Result<Self, CannotMove> {
match self.typ {
Type::Base(_) | Type::Contract(_) => {
if self.location != Location::Value {
self.move_location = Some(Location::Value);
}
Ok(self)
}
_ => Err(CannotMove),
}
}
/// The final location of an expression after a possible move.
pub fn final_location(&self) -> Location {
if let Some(location) = self.move_location {
return location;
}
self.location
}
}
impl fmt::Display for ExpressionAttributes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
if let Some(move_to) = self.move_location {
write!(f, "{}: {:?} => {:?}", self.typ, self.location, move_to)
} else {
write!(f, "{}: {:?}", self.typ, self.location)
}
}
}
/// The type of a function call.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CallType {
BuiltinFunction(GlobalFunction),
Intrinsic(Intrinsic),
BuiltinValueMethod {
method: ValueMethod,
typ: Type,
},
// create, create2 (will be methods of the context struct soon)
BuiltinAssociatedFunction {
contract: ContractId,
function: ContractTypeMethod,
},
// MyStruct.foo() (soon MyStruct::foo())
AssociatedFunction {
class: Class,
function: FunctionId,
},
// some_struct_or_contract.foo()
ValueMethod {
class: Class,
method: FunctionId,
},
// some_trait.foo()
// The reason this can not use `ValueMethod` is mainly because the trait might not have a function implementation
// and even if it had it might not be the one that ends up getting executed. An `impl` block will decide that.
TraitValueMethod {
trait_id: TraitId,
method: FunctionSigId,
// Traits can not directly be used as types but can act as bounds for generics. This is the generic type
// that the method is called on.
generic_type: Generic,
},
External {
contract: ContractId,
function: FunctionId,
},
Pure(FunctionId),
TypeConstructor(Type),
}
impl CallType {
pub fn function(&self) -> Option<FunctionId> {
use CallType::*;
match self {
BuiltinFunction(_)
| BuiltinValueMethod { .. }
| TypeConstructor(_)
| Intrinsic(_)
| TraitValueMethod { .. }
| BuiltinAssociatedFunction { .. } => None,
AssociatedFunction { function: id, .. }
| ValueMethod { method: id, .. }
| External { function: id, .. }
| Pure(id) => Some(*id),
}
}
pub fn function_name(&self, db: &dyn AnalyzerDb) -> SmolStr {
match self {
CallType::BuiltinFunction(f) => f.as_ref().into(),
CallType::Intrinsic(f) => f.as_ref().into(),
CallType::BuiltinValueMethod { method, .. } => method.as_ref().into(),
CallType::BuiltinAssociatedFunction { function, .. } => function.as_ref().into(),
CallType::AssociatedFunction { function: id, .. }
| CallType::ValueMethod { method: id, .. }
| CallType::External { function: id, .. }
| CallType::Pure(id) => id.name(db),
CallType::TraitValueMethod { method: id, .. } => id.name(db),
CallType::TypeConstructor(typ) => typ.name(),
}
}
pub fn is_unsafe(&self, db: &dyn AnalyzerDb) -> bool {
if let CallType::Intrinsic(_) = self {
true
} else if let CallType::TypeConstructor(Type::Struct(struct_)) = self {
// check that this is the `Context` struct defined in `std`
// this should be deleted once associated functions are supported and we can
// define unsafe constructors in Fe
struct_.name == "Context" && struct_.id.module(db).is_in_std(db)
} else {
self.function().map(|id| id.is_unsafe(db)).unwrap_or(false)
}
}
}
impl fmt::Display for CallType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{:?}", self)
}
}
/// Represents constant value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Constant {
Int(BigInt),
Bool(bool),
Str(SmolStr),
}