-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathcontracts.rs
424 lines (382 loc) · 13.7 KB
/
contracts.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
use crate::context::{AnalyzerContext, NamedThing};
use crate::db::{Analysis, AnalyzerDb};
use crate::errors;
use crate::namespace::items::{
self, ContractFieldId, ContractId, DepGraph, DepGraphWrapper, DepLocality, EventId, FunctionId,
Item, TypeDef,
};
use crate::namespace::scopes::ItemScope;
use crate::namespace::types::{self, Contract, Struct, Type};
use crate::traversal::types::type_desc;
use fe_common::diagnostics::Label;
use fe_parser::ast;
use indexmap::map::{Entry, IndexMap};
use smol_str::SmolStr;
use std::rc::Rc;
/// A `Vec` of every function defined in the contract, including duplicates and
/// the init function.
pub fn contract_all_functions(db: &dyn AnalyzerDb, contract: ContractId) -> Rc<[FunctionId]> {
let module = contract.module(db);
let body = &contract.data(db).ast.kind.body;
body.iter()
.filter_map(|stmt| match stmt {
ast::ContractStmt::Event(_) => None,
ast::ContractStmt::Function(node) => Some(db.intern_function(Rc::new(
items::Function::new(db, node, Some(items::Class::Contract(contract)), module),
))),
})
.collect()
}
pub fn contract_function_map(
db: &dyn AnalyzerDb,
contract: ContractId,
) -> Analysis<Rc<IndexMap<SmolStr, FunctionId>>> {
let scope = ItemScope::new(db, contract.module(db));
let mut map = IndexMap::<SmolStr, FunctionId>::new();
for func in db.contract_all_functions(contract).iter() {
let def = &func.data(db).ast;
let def_name = def.name();
if def_name == "__init__" || def_name == "__call__" {
continue;
}
if let Some(event) = contract.event(db, def_name) {
scope.name_conflict_error(
"function",
def_name,
&NamedThing::Item(Item::Event(event)),
Some(event.name_span(db)),
def.kind.sig.kind.name.span,
);
continue;
}
if let Ok(Some(named_item)) = scope.resolve_name(def_name, func.name_span(db)) {
scope.name_conflict_error(
"function",
def_name,
&named_item,
named_item.name_span(db),
def.kind.sig.kind.name.span,
);
continue;
}
match map.entry(def.name().into()) {
Entry::Occupied(entry) => {
scope.duplicate_name_error(
&format!(
"duplicate function names in `contract {}`",
contract.name(db),
),
entry.key(),
entry.get().data(db).ast.span,
def.span,
);
}
Entry::Vacant(entry) => {
entry.insert(*func);
}
}
}
Analysis {
value: Rc::new(map),
diagnostics: scope.diagnostics.take().into(),
}
}
pub fn contract_public_function_map(
db: &dyn AnalyzerDb,
contract: ContractId,
) -> Rc<IndexMap<SmolStr, FunctionId>> {
Rc::new(
contract
.functions(db)
.iter()
.filter_map(|(name, func)| func.is_public(db).then(|| (name.clone(), *func)))
.collect(),
)
}
pub fn contract_init_function(
db: &dyn AnalyzerDb,
contract: ContractId,
) -> Analysis<Option<FunctionId>> {
let all_fns = db.contract_all_functions(contract);
let mut init_fns = all_fns.iter().filter_map(|func| {
let def = &func.data(db).ast;
(def.name() == "__init__").then(|| (func, def.span))
});
let mut diagnostics = vec![];
let first_def = init_fns.next();
if let Some((_, dupe_span)) = init_fns.next() {
let mut labels = vec![
Label::primary(first_def.unwrap().1, "`__init__` first defined here"),
Label::secondary(dupe_span, "`init` redefined here"),
];
for (_, dupe_span) in init_fns {
labels.push(Label::secondary(dupe_span, "`__init__` redefined here"));
}
diagnostics.push(errors::fancy_error(
&format!(
"`fn __init__()` is defined multiple times in `contract {}`",
contract.name(db),
),
labels,
vec![],
));
}
if let Some((id, span)) = first_def {
// `__init__` must be `pub`.
// Return type is checked in `queries::functions::function_signature`.
if !id.is_public(db) {
diagnostics.push(errors::fancy_error(
"`__init__` function is not public",
vec![Label::primary(span, "`__init__` function must be public")],
vec![
"Hint: Add the `pub` modifier.".to_string(),
"Example: `pub fn __init__():`".to_string(),
],
));
}
}
Analysis {
value: first_def.map(|(id, _span)| *id),
diagnostics: diagnostics.into(),
}
}
pub fn contract_call_function(
db: &dyn AnalyzerDb,
contract: ContractId,
) -> Analysis<Option<FunctionId>> {
let all_fns = db.contract_all_functions(contract);
let mut call_fns = all_fns.iter().filter_map(|func| {
let def = &func.data(db).ast;
(def.name() == "__call__").then(|| (func, def.span))
});
let mut diagnostics = vec![];
let first_def = call_fns.next();
if let Some((_, dupe_span)) = call_fns.next() {
let mut labels = vec![
Label::primary(first_def.unwrap().1, "`__call__` first defined here"),
Label::secondary(dupe_span, "`__call__` redefined here"),
];
for (_, dupe_span) in call_fns {
labels.push(Label::secondary(dupe_span, "`__call__` redefined here"));
}
diagnostics.push(errors::fancy_error(
&format!(
"`fn __call__()` is defined multiple times in `contract {}`",
contract.name(db),
),
labels,
vec![],
));
}
if let Some((id, span)) = first_def {
// `__call__` must be `pub`.
// Return type is checked in `queries::functions::function_signature`.
if !id.is_public(db) {
diagnostics.push(errors::fancy_error(
"`__call__` function is not public",
vec![Label::primary(span, "`__call__` function must be public")],
vec![
"Hint: Add the `pub` modifier.".to_string(),
"Example: `pub fn __call__():`".to_string(),
],
));
}
}
if let Some((_id, init_span)) = first_def {
for func in all_fns.iter() {
let name = func.name(db);
if func.is_public(db) && name != "__init__" && name != "__call__" {
diagnostics.push(errors::fancy_error(
"`pub` not allowed if `__call__` is defined",
vec![
Label::primary(func.name_span(db), &format!("`{}` can't be public", name)),
Label::secondary(init_span, "`__call__` defined here"),
],
vec![
"The `__call__` function replaces the default function dispatcher, which makes `pub` modifiers obsolete.".to_string(),
"Hint: Remove the `pub` modifier or `__call__` function.".to_string(),
],
));
}
}
}
Analysis {
value: first_def.map(|(id, _span)| *id),
diagnostics: diagnostics.into(),
}
}
/// A `Vec` of all events defined within the contract, including those with
/// duplicate names.
pub fn contract_all_events(db: &dyn AnalyzerDb, contract: ContractId) -> Rc<[EventId]> {
let body = &contract.data(db).ast.kind.body;
body.iter()
.filter_map(|stmt| match stmt {
ast::ContractStmt::Function(_) => None,
ast::ContractStmt::Event(node) => Some(db.intern_event(Rc::new(items::Event {
ast: node.clone(),
module: contract.module(db),
contract: Some(contract),
}))),
})
.collect()
}
pub fn contract_event_map(
db: &dyn AnalyzerDb,
contract: ContractId,
) -> Analysis<Rc<IndexMap<SmolStr, EventId>>> {
let scope = ItemScope::new(db, contract.module(db));
let mut map = IndexMap::<SmolStr, EventId>::new();
let contract_name = contract.name(db);
for event in db.contract_all_events(contract).iter() {
let node = &event.data(db).ast;
match map.entry(node.name().into()) {
Entry::Occupied(entry) => {
scope.duplicate_name_error(
&format!("duplicate event names in `contract {}`", contract_name,),
entry.key(),
entry.get().data(db).ast.span,
node.span,
);
}
Entry::Vacant(entry) => {
entry.insert(*event);
}
}
}
Analysis {
value: Rc::new(map),
diagnostics: scope.diagnostics.take().into(),
}
}
/// All field ids, including those with duplicate names
pub fn contract_all_fields(db: &dyn AnalyzerDb, contract: ContractId) -> Rc<[ContractFieldId]> {
contract
.data(db)
.ast
.kind
.fields
.iter()
.map(|node| {
db.intern_contract_field(Rc::new(items::ContractField {
ast: node.clone(),
parent: contract,
}))
})
.collect()
}
pub fn contract_field_map(
db: &dyn AnalyzerDb,
contract: ContractId,
) -> Analysis<Rc<IndexMap<SmolStr, ContractFieldId>>> {
let scope = ItemScope::new(db, contract.module(db));
let mut map = IndexMap::<SmolStr, ContractFieldId>::new();
let contract_name = contract.name(db);
for field in db.contract_all_fields(contract).iter() {
let node = &field.data(db).ast;
match map.entry(node.name().into()) {
Entry::Occupied(entry) => {
scope.duplicate_name_error(
&format!("duplicate field names in `contract {}`", contract_name,),
entry.key(),
entry.get().data(db).ast.span,
node.span,
);
}
Entry::Vacant(entry) => {
entry.insert(*field);
}
}
}
Analysis {
value: Rc::new(map),
diagnostics: scope.diagnostics.take().into(),
}
}
pub fn contract_field_type(
db: &dyn AnalyzerDb,
field: ContractFieldId,
) -> Analysis<Result<types::Type, errors::TypeError>> {
let mut scope = ItemScope::new(db, field.data(db).parent.module(db));
let typ = type_desc(&mut scope, &field.data(db).ast.kind.typ);
let node = &field.data(db).ast;
if node.kind.is_pub {
scope.not_yet_implemented("contract `pub` fields", node.span);
}
if node.kind.is_const {
scope.not_yet_implemented("contract `const` fields", node.span);
}
if let Some(value_node) = &node.kind.value {
scope.not_yet_implemented("contract field initial value assignment", value_node.span);
}
Analysis {
value: typ,
diagnostics: scope.diagnostics.take().into(),
}
}
pub fn contract_dependency_graph(db: &dyn AnalyzerDb, contract: ContractId) -> DepGraphWrapper {
// A contract depends on the types of its fields, and the things those types
// depend on. Note that this *does not* include the contract's public
// function graph. (See `contract_runtime_dependency_graph` below)
let fields = contract.fields(db);
let field_types = fields
.values()
.filter_map(|field| match field.typ(db).ok()? {
// We don't want
Type::Contract(Contract { id, .. }) => Some(Item::Type(TypeDef::Contract(id))),
Type::Struct(Struct { id, .. }) => Some(Item::Type(TypeDef::Struct(id))),
// TODO: when tuples can contain non-primitive items,
// we'll have to depend on tuple element types
_ => None,
})
.collect::<Vec<_>>();
let root = Item::Type(TypeDef::Contract(contract));
let mut graph = DepGraph::from_edges(
field_types
.iter()
.map(|item| (root, *item, DepLocality::Local)),
);
for item in field_types {
if let Some(subgraph) = item.dependency_graph(db) {
graph.extend(subgraph.all_edges())
}
}
DepGraphWrapper(Rc::new(graph))
}
pub fn contract_dependency_graph_cycle(
_db: &dyn AnalyzerDb,
_cycle: &[String],
_contract: &ContractId,
) -> DepGraphWrapper {
DepGraphWrapper(Rc::new(DepGraph::new()))
}
pub fn contract_runtime_dependency_graph(
db: &dyn AnalyzerDb,
contract: ContractId,
) -> DepGraphWrapper {
// This is the dependency graph of the (as yet imaginary) `__call__` function,
// which dispatches to the contract's public functions. This should be used
// when compiling the runtime object for a contract.
let root = Item::Type(TypeDef::Contract(contract));
let root_fns = if let Some(call_id) = contract.call_function(db) {
vec![call_id]
} else {
contract.public_functions(db).values().copied().collect()
}
.into_iter()
.map(|fun| (root, Item::Function(fun), DepLocality::Local))
.collect::<Vec<_>>();
let mut graph = DepGraph::from_edges(root_fns.iter());
for (_, item, _) in root_fns {
if let Some(subgraph) = item.dependency_graph(db) {
graph.extend(subgraph.all_edges())
}
}
DepGraphWrapper(Rc::new(graph))
}
pub fn contract_runtime_dependency_graph_cycle(
_db: &dyn AnalyzerDb,
_cycle: &[String],
_contract: &ContractId,
) -> DepGraphWrapper {
DepGraphWrapper(Rc::new(DepGraph::new()))
}