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
use super::core::{self, Subst, TParamSubst};
use crate::{
diagnostics::{codes::TypeSafety, Diagnostic},
expansion::ast::ModuleIdent,
naming::ast::{self as N, TParam, TParamID, Type, Type_},
parser::ast::FunctionName,
shared::{unique_map::UniqueMap, CompilationEnv},
typing::ast as T,
};
use move_ir_types::location::*;
use move_symbol_pool::Symbol;
use petgraph::{
algo::{astar as petgraph_astar, tarjan_scc as petgraph_scc},
graphmap::DiGraphMap,
};
use std::collections::BTreeMap;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Edge {
Identity,
Nested,
}
#[derive(Clone, Debug)]
struct EdgeInfo {
name: FunctionName,
type_argument: Type,
loc: Loc,
edge: Edge,
}
struct Context<'a> {
tparams: &'a BTreeMap<ModuleIdent, BTreeMap<FunctionName, &'a Vec<TParam>>>,
tparam_type_arguments: BTreeMap<TParam, BTreeMap<TParam, EdgeInfo>>,
current_module: ModuleIdent,
}
impl<'a> Context<'a> {
fn new(
tparams: &'a BTreeMap<ModuleIdent, BTreeMap<FunctionName, &'a Vec<TParam>>>,
current_module: ModuleIdent,
) -> Self {
Context {
tparams,
current_module,
tparam_type_arguments: BTreeMap::new(),
}
}
fn add_usage(&mut self, loc: Loc, module: &ModuleIdent, fname: &FunctionName, targs: &[Type]) {
if &self.current_module != module {
return;
}
self.tparams[module][fname]
.iter()
.zip(targs)
.for_each(|(tparam, targ)| {
let info = EdgeInfo {
name: *fname,
type_argument: targ.clone(),
loc,
edge: Edge::Identity,
};
Self::add_tparam_edges(&mut self.tparam_type_arguments, tparam, info, targ)
})
}
fn add_tparam_edges(
acc: &mut BTreeMap<TParam, BTreeMap<TParam, EdgeInfo>>,
tparam: &TParam,
info: EdgeInfo,
sp!(_, targ_): &Type,
) {
use N::Type_::*;
match targ_ {
Var(_) => panic!("ICE tvar after expansion"),
Unit | Anything | UnresolvedError => (),
Ref(_, t) => {
let info = EdgeInfo {
edge: Edge::Nested,
..info
};
Self::add_tparam_edges(acc, tparam, info, t)
}
Apply(_, _, tys) => {
let info = EdgeInfo {
edge: Edge::Nested,
..info
};
tys.iter()
.for_each(|t| Self::add_tparam_edges(acc, tparam, info.clone(), t))
}
Param(tp) => {
let tp_neighbors = acc.entry(tp.clone()).or_insert_with(BTreeMap::new);
match tp_neighbors.get(tparam) {
Some(EdgeInfo {
edge: Edge::Nested, ..
}) => (),
None
| Some(EdgeInfo {
edge: Edge::Identity,
..
}) => {
tp_neighbors.insert(tparam.clone(), info);
}
}
}
}
}
fn instantiation_graph(&self) -> DiGraphMap<&TParam, Edge> {
let edges = self
.tparam_type_arguments
.iter()
.flat_map(|(parent, children)| {
children
.iter()
.map(move |(child, info)| (parent, child, info.edge))
});
DiGraphMap::from_edges(edges)
}
}
pub fn modules(
compilation_env: &mut CompilationEnv,
modules: &UniqueMap<ModuleIdent, T::ModuleDefinition>,
) {
let tparams = modules
.key_cloned_iter()
.map(|(mname, mdef)| {
let tparams = mdef
.functions
.key_cloned_iter()
.map(|(fname, fdef)| (fname, &fdef.signature.type_parameters))
.collect();
(mname, tparams)
})
.collect();
modules
.key_cloned_iter()
.for_each(|(mname, m)| module(compilation_env, &tparams, mname, m))
}
macro_rules! scc_edges {
($graph:expr, $scc:expr) => {{
let g = $graph;
let s = $scc;
s.iter().flat_map(move |v| {
s.iter()
.filter_map(move |u| g.edge_weight(v, u).cloned().map(|e| (v, e, u)))
})
}};
}
fn module<'a>(
compilation_env: &mut CompilationEnv,
tparams: &'a BTreeMap<ModuleIdent, BTreeMap<FunctionName, &'a Vec<TParam>>>,
mname: ModuleIdent,
module: &T::ModuleDefinition,
) {
let context = &mut Context::new(tparams, mname);
module
.functions
.key_cloned_iter()
.for_each(|(_fname, fdef)| function_body(context, &fdef.body));
let graph = context.instantiation_graph();
petgraph_scc(&graph)
.into_iter()
.filter(|scc| scc_edges!(&graph, scc).any(|(_, e, _)| e == Edge::Nested))
.for_each(|scc| compilation_env.add_diag(cycle_error(context, &graph, scc)))
}
fn function_body(context: &mut Context, sp!(_, b_): &T::FunctionBody) {
match b_ {
T::FunctionBody_::Native => (),
T::FunctionBody_::Defined(es) => sequence(context, es),
}
}
fn sequence(context: &mut Context, seq: &T::Sequence) {
seq.iter().for_each(|item| sequence_item(context, item))
}
fn sequence_item(context: &mut Context, item: &T::SequenceItem) {
use T::SequenceItem_ as S;
match &item.value {
S::Bind(_, _, te) | S::Seq(te) => exp(context, te),
S::Declare(_) => (),
}
}
fn exp(context: &mut Context, e: &T::Exp) {
use T::UnannotatedExp_ as E;
match &e.exp.value {
E::Use(_) => panic!("ICE should have been expanded"),
E::Unit { .. }
| E::Value(_)
| E::Constant(_, _)
| E::Move { .. }
| E::Copy { .. }
| E::BorrowLocal(_, _)
| E::Break
| E::Continue
| E::Spec(_, _)
| E::UnresolvedError => (),
E::ModuleCall(call) => {
context.add_usage(e.exp.loc, &call.module, &call.name, &call.type_arguments);
exp(context, &call.arguments)
}
E::IfElse(eb, et, ef) => {
exp(context, eb);
exp(context, et);
exp(context, ef);
}
E::While(eb, eloop) => {
exp(context, eb);
exp(context, eloop);
}
E::Loop { body: eloop, .. } => exp(context, eloop),
E::Block(seq) => sequence(context, seq),
E::Assign(_, _, er) => exp(context, er),
E::Builtin(_, er)
| E::Return(er)
| E::Abort(er)
| E::Dereference(er)
| E::UnaryExp(_, er)
| E::Borrow(_, er, _)
| E::TempBorrow(_, er) => exp(context, er),
E::Mutate(el, er) | E::BinopExp(el, _, _, er) => {
exp(context, el);
exp(context, er)
}
E::Pack(_, _, _, fields) => {
for (_, _, (_, (_, fe))) in fields.iter() {
exp(context, fe)
}
}
E::ExpList(el) => exp_list(context, el),
E::Cast(e, _) | E::Annotate(e, _) => exp(context, e),
}
}
fn exp_list(context: &mut Context, items: &[T::ExpListItem]) {
items.iter().for_each(|item| exp_list_item(context, item))
}
fn exp_list_item(context: &mut Context, item: &T::ExpListItem) {
use T::ExpListItem as I;
match item {
I::Single(e, _) | I::Splat(_, e, _) => {
exp(context, e);
}
}
}
fn cycle_error(
context: &Context,
graph: &DiGraphMap<&TParam, Edge>,
scc: Vec<&TParam>,
) -> Diagnostic {
let critical_edge = scc_edges!(graph, &scc).find(|(_, e, _)| e == &Edge::Nested);
let (critical_tail, _, critical_head) = critical_edge.unwrap();
let (_, cycle_nodes) = petgraph_astar(
graph,
critical_head,
|finish| &finish == critical_tail,
|_e| 1,
|_| 0,
)
.unwrap();
assert!(!cycle_nodes.is_empty());
let next = |i| (i + 1) % cycle_nodes.len();
let prev = |i: usize| i.checked_sub(1).unwrap_or(cycle_nodes.len() - 1);
assert!(&cycle_nodes[0] == critical_head);
let param_info = &context.tparam_type_arguments[cycle_nodes[0]][cycle_nodes[next(0)]];
let arg_info = &context.tparam_type_arguments[cycle_nodes[prev(0)]][cycle_nodes[0]];
let call_loc = arg_info.loc;
let call_msg = format!(
"Invalid call to '{}::{}'",
&context.current_module, &arg_info.name,
);
let ty_loc = arg_info.type_argument.loc;
let ty_str = core::error_format(&arg_info.type_argument, &Subst::empty());
let case = match cycle_nodes.len() {
1 => "This recursive call",
2 => "These mutually recursive calls",
_ => "A cycle of recursive calls",
};
let tparam_msg = format!(
"The type parameter '{param_n}::{param_t}' was instantiated with the type {ty}, which \
contains the type parameter '{arg_n}::{arg_t}'. {case} causes the instantiation to \
recurse infinitely",
param_n = ¶m_info.name,
param_t = &critical_head.user_specified_name,
ty = ty_str,
arg_n = &arg_info.name,
arg_t = &critical_tail.user_specified_name,
case = case,
);
let mut secondary_labels = vec![(ty_loc, tparam_msg)];
if cycle_nodes.len() > 1 {
let (mut subst, init_call) = {
let ftparam = cycle_nodes[0];
let prev_tparam = cycle_nodes[prev(0)];
let init_state = &context.tparam_type_arguments[prev_tparam][ftparam];
let ftparam_ty = {
let qualified_ = Symbol::from(format!(
"{}::{}",
&init_state.name, &ftparam.user_specified_name
));
let qualified = sp(ftparam.user_specified_name.loc, qualified_);
let qualified_tp = TParam {
user_specified_name: qualified,
..ftparam.clone()
};
sp(init_state.loc, Type_::Param(qualified_tp))
};
let init_call = make_call_string(context, init_state, ftparam.id, &ftparam_ty);
let loc = ftparam.user_specified_name.loc;
let subst = make_subst(context, loc, init_state, ftparam.id, ftparam_ty);
(subst, init_call)
};
let cycle_calls = cycle_nodes
.iter()
.enumerate()
.map(|(i, targ_tparam)| {
let tparam = cycle_nodes[next(i)];
let cur = &context.tparam_type_arguments[targ_tparam][tparam];
let targ = core::subst_tparams(&subst, cur.type_argument.clone());
let res = make_call_string(context, cur, tparam.id, &targ);
let loc = tparam.user_specified_name.loc;
subst = make_subst(context, loc, cur, tparam.id, targ);
res
})
.collect::<Vec<_>>();
cycle_calls
.iter()
.enumerate()
.for_each(|(i, (loc, next_call))| {
let (_, prev_call) = if i == 0 {
&init_call
} else {
&cycle_calls[prev(i)]
};
let msg = format!("'{}' calls '{}'", prev_call, next_call);
secondary_labels.push((*loc, msg))
});
}
Diagnostic::new(
TypeSafety::CyclicInstantiation,
(call_loc, call_msg),
secondary_labels,
)
}
fn make_subst(
context: &Context,
loc: Loc,
state: &EdgeInfo,
tparam: TParamID,
tparam_ty: Type,
) -> TParamSubst {
let mut tparam_ty = Some(tparam_ty);
context.tparams[&context.current_module][&state.name]
.iter()
.map(|tp| {
let ty = if tp.id == tparam {
tparam_ty.take().unwrap()
} else {
sp(loc, Type_::Anything)
};
(tp.id, ty)
})
.collect::<TParamSubst>()
}
fn make_call_string(
context: &Context,
cur: &EdgeInfo,
tparam: TParamID,
targ: &Type,
) -> (Loc, String) {
let targs = context.tparams[&context.current_module][&cur.name]
.iter()
.map(|tp| {
if tp.id == tparam {
core::error_format_nested(targ, &Subst::empty())
} else {
"_".to_owned()
}
})
.collect::<Vec<_>>()
.join(", ");
let targs = if targs.is_empty() {
targs
} else {
format!("<{}>", targs)
};
(cur.loc, format!("{}{}", &cur.name, targs))
}