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
use std::collections::HashMap;
use crate::{
ast::{
ArgName, DataType, Definition, Function, Layer, ModuleConstant, ModuleKind,
RecordConstructor, RecordConstructorArg, Span, Tracing, TypeAlias, TypedDefinition,
TypedFunction, TypedModule, UntypedDefinition, UntypedModule, Use, Validator,
},
builtins,
builtins::function,
IdGenerator,
};
use super::{
environment::{generalise, EntityKind, Environment},
error::{Error, Warning},
expr::ExprTyper,
hydrator::Hydrator,
TypeInfo, ValueConstructor, ValueConstructorVariant,
};
const PUB_OFFSET: usize = 3;
impl UntypedModule {
pub fn infer(
mut self,
id_gen: &IdGenerator,
kind: ModuleKind,
package: &str,
modules: &HashMap<String, TypeInfo>,
tracing: Tracing,
warnings: &mut Vec<Warning>,
) -> Result<TypedModule, Error> {
let name = self.name.clone();
let docs = std::mem::take(&mut self.docs);
let mut environment = Environment::new(id_gen.clone(), &name, modules, warnings);
let mut type_names = HashMap::with_capacity(self.definitions.len());
let mut value_names = HashMap::with_capacity(self.definitions.len());
let mut hydrators = HashMap::with_capacity(self.definitions.len());
// Register any modules, types, and values being imported
// We process imports first so that anything imported can be referenced
// anywhere in the module.
for def in self.definitions() {
environment.register_import(def)?;
}
// Register types so they can be used in constructors and functions
// earlier in the module.
environment.register_types(
self.definitions.iter().collect(),
&name,
&mut hydrators,
&mut type_names,
)?;
// Register values so they can be used in functions earlier in the module.
for def in self.definitions() {
environment.register_values(def, &name, &mut hydrators, &mut value_names, kind)?;
}
// Infer the types of each definition in the module
// We first infer all the constants so they can be used in functions defined
// anywhere in the module.
let mut definitions = Vec::with_capacity(self.definitions.len());
let mut consts = vec![];
let mut not_consts = vec![];
for def in self.definitions().cloned() {
match def {
Definition::ModuleConstant { .. } => consts.push(def),
Definition::Validator { .. } if kind.is_validator() => not_consts.push(def),
Definition::Validator { .. } => (),
Definition::Fn { .. }
| Definition::Test { .. }
| Definition::TypeAlias { .. }
| Definition::DataType { .. }
| Definition::Use { .. } => not_consts.push(def),
}
}
for def in consts.into_iter().chain(not_consts) {
let definition =
infer_definition(def, &name, &mut hydrators, &mut environment, tracing, kind)?;
definitions.push(definition);
}
// Generalise functions now that the entire module has been inferred
let definitions = definitions
.into_iter()
.map(|def| environment.generalise_definition(def, &name))
.collect();
// Generate warnings for unused items
environment.convert_unused_to_warnings();
// Remove private and imported types and values to create the public interface
environment
.module_types
.retain(|_, info| info.public && info.module == name);
environment.module_values.retain(|_, info| info.public);
environment
.accessors
.retain(|_, accessors| accessors.public);
// Ensure no exported values have private types in their type signature
for value in environment.module_values.values() {
if let Some(leaked) = value.tipo.find_private_type() {
return Err(Error::PrivateTypeLeak {
location: value.variant.location(),
leaked,
});
}
}
let Environment {
module_types: types,
module_types_constructors: types_constructors,
module_values: values,
accessors,
..
} = environment;
Ok(TypedModule {
docs,
name: name.clone(),
definitions,
kind,
type_info: TypeInfo {
name,
types,
types_constructors,
values,
accessors,
kind,
package: package.to_string(),
},
})
}
}
fn infer_definition(
def: UntypedDefinition,
module_name: &String,
hydrators: &mut HashMap<String, Hydrator>,
environment: &mut Environment<'_>,
tracing: Tracing,
kind: ModuleKind,
) -> Result<TypedDefinition, Error> {
match def {
Definition::Fn(Function {
doc,
location,
name,
public,
arguments: args,
body,
return_annotation,
end_position,
can_error,
..
}) => {
if public && kind.is_validator() {
environment.warnings.push(Warning::PubInValidatorModule {
location: Span {
start: location.start,
end: location.start + PUB_OFFSET,
},
})
}
let preregistered_fn = environment
.get_variable(&name)
.expect("Could not find preregistered type for function");
let field_map = preregistered_fn.field_map().cloned();
let preregistered_type = preregistered_fn.tipo.clone();
let (args_types, return_type) = preregistered_type
.function_types()
.expect("Preregistered type for fn was not a fn");
// Infer the type using the preregistered args + return types as a starting point
let (tipo, args, body, safe_to_generalise) =
environment.in_new_scope(|environment| {
let args = args
.into_iter()
.zip(&args_types)
.map(|(arg_name, tipo)| arg_name.set_type(tipo.clone()))
.collect();
let mut expr_typer = ExprTyper::new(environment, tracing);
expr_typer.hydrator = hydrators
.remove(&name)
.expect("Could not find hydrator for fn");
let (args, body) =
expr_typer.infer_fn_with_known_types(args, body, Some(return_type))?;
let args_types = args.iter().map(|a| a.tipo.clone()).collect();
let tipo = function(args_types, body.tipo());
let safe_to_generalise = !expr_typer.ungeneralised_function_used;
Ok::<_, Error>((tipo, args, body, safe_to_generalise))
})?;
// Assert that the inferred type matches the type of any recursive call
environment.unify(preregistered_type, tipo.clone(), location, false)?;
// Generalise the function if safe to do so
let tipo = if safe_to_generalise {
environment.ungeneralised_functions.remove(&name);
let tipo = generalise(tipo, 0);
let module_fn = ValueConstructorVariant::ModuleFn {
name: name.clone(),
field_map,
module: module_name.to_owned(),
arity: args.len(),
location,
builtin: None,
};
environment.insert_variable(name.clone(), module_fn, tipo.clone());
tipo
} else {
tipo
};
Ok(Definition::Fn(Function {
doc,
location,
name,
public,
arguments: args,
return_annotation,
return_type: tipo
.return_type()
.expect("Could not find return type for fn"),
body,
can_error,
end_position,
}))
}
Definition::Validator(Validator {
doc,
location,
end_position,
mut fun,
other_fun,
params,
}) => {
let params_length = params.len();
let temp_params = params.iter().cloned().chain(fun.arguments);
fun.arguments = temp_params.collect();
environment.in_new_scope(|environment| {
let preregistered_fn = environment
.get_variable(&fun.name)
.expect("Could not find preregistered type for function");
let preregistered_type = preregistered_fn.tipo.clone();
let (args_types, _return_type) = preregistered_type
.function_types()
.expect("Preregistered type for fn was not a fn");
for (arg, t) in params.iter().zip(args_types[0..params.len()].iter()) {
match &arg.arg_name {
ArgName::Named {
name,
is_validator_param,
..
} if *is_validator_param => {
environment.insert_variable(
name.to_string(),
ValueConstructorVariant::LocalVariable {
location: arg.location,
},
t.clone(),
);
environment.init_usage(
name.to_string(),
EntityKind::Variable,
arg.location,
);
}
ArgName::Named { .. } | ArgName::Discarded { .. } => (),
};
}
let Definition::Fn(mut typed_fun) = infer_definition(
Definition::Fn(fun),
module_name,
hydrators,
environment,
tracing,
kind,
)? else {
unreachable!("validator definition inferred as something other than a function?")
};
if !typed_fun.return_type.is_bool() {
return Err(Error::ValidatorMustReturnBool {
return_type: typed_fun.return_type.clone(),
location: typed_fun.location,
});
}
let typed_params = typed_fun.arguments.drain(0..params_length).collect();
if typed_fun.arguments.len() < 2 || typed_fun.arguments.len() > 3 {
return Err(Error::IncorrectValidatorArity {
count: typed_fun.arguments.len() as u32,
location: typed_fun.location,
});
}
let typed_other_fun = other_fun
.map(|mut other| -> Result<TypedFunction, Error> {
let params = params.into_iter().chain(other.arguments);
other.arguments = params.collect();
let Definition::Fn(mut other_typed_fun) = infer_definition(
Definition::Fn(other),
module_name,
hydrators,
environment,
tracing,
kind,
)? else {
unreachable!(
"validator definition inferred as something other than a function?"
)
};
if !other_typed_fun.return_type.is_bool() {
return Err(Error::ValidatorMustReturnBool {
return_type: other_typed_fun.return_type.clone(),
location: other_typed_fun.location,
});
}
other_typed_fun.arguments.drain(0..params_length);
if other_typed_fun.arguments.len() < 2
|| other_typed_fun.arguments.len() > 3
{
return Err(Error::IncorrectValidatorArity {
count: other_typed_fun.arguments.len() as u32,
location: other_typed_fun.location,
});
}
if typed_fun.arguments.len() == other_typed_fun.arguments.len() {
return Err(Error::MultiValidatorEqualArgs {
location: typed_fun.location,
other_location: other_typed_fun.location,
count: other_typed_fun.arguments.len(),
});
}
Ok(other_typed_fun)
})
.transpose();
Ok(Definition::Validator(Validator {
doc,
end_position,
fun: typed_fun,
other_fun: typed_other_fun?,
location,
params: typed_params,
}))
})
}
Definition::Test(f) => {
if let Definition::Fn(f) = infer_definition(
Definition::Fn(f),
module_name,
hydrators,
environment,
tracing,
kind,
)? {
environment.unify(f.return_type.clone(), builtins::bool(), f.location, false)?;
Ok(Definition::Test(f))
} else {
unreachable!("test definition inferred as something other than a function?")
}
}
Definition::TypeAlias(TypeAlias {
doc,
location,
public,
alias,
parameters,
annotation,
..
}) => {
if public && kind.is_validator() {
environment.warnings.push(Warning::PubInValidatorModule {
location: Span {
start: location.start,
end: location.start + PUB_OFFSET,
},
})
}
let tipo = environment
.get_type_constructor(&None, &alias, location)
.expect("Could not find existing type for type alias")
.tipo
.clone();
Ok(Definition::TypeAlias(TypeAlias {
doc,
location,
public,
alias,
parameters,
annotation,
tipo,
}))
}
Definition::DataType(DataType {
doc,
location,
public,
opaque,
name,
parameters,
constructors: untyped_constructors,
..
}) => {
if public && kind.is_validator() {
environment.warnings.push(Warning::PubInValidatorModule {
location: Span {
start: location.start,
end: location.start + PUB_OFFSET,
},
})
}
let constructors = untyped_constructors
.into_iter()
.map(
|RecordConstructor {
location,
name,
arguments: args,
doc,
sugar,
}| {
let preregistered_fn = environment
.get_variable(&name)
.expect("Could not find preregistered type for function");
let preregistered_type = preregistered_fn.tipo.clone();
let args = if let Some((args_types, _return_type)) =
preregistered_type.function_types()
{
args.into_iter()
.zip(&args_types)
.map(
|(
RecordConstructorArg {
label,
annotation,
location,
doc,
..
},
t,
)| {
RecordConstructorArg {
label,
annotation,
location,
tipo: t.clone(),
doc,
}
},
)
.collect()
} else {
vec![]
};
RecordConstructor {
location,
name,
arguments: args,
doc,
sugar,
}
},
)
.collect();
let typed_parameters = environment
.get_type_constructor(&None, &name, location)
.expect("Could not find preregistered type constructor ")
.parameters
.clone();
let typed_data = DataType {
doc,
location,
public,
opaque,
name,
parameters,
constructors,
typed_parameters,
};
for constr in &typed_data.constructors {
for RecordConstructorArg { tipo, location, .. } in &constr.arguments {
if tipo.is_function() {
return Err(Error::FunctionTypeInData {
location: *location,
});
}
}
}
Ok(Definition::DataType(typed_data))
}
Definition::Use(Use {
location,
module,
as_name,
mut unqualified,
..
}) => {
let name = module.join("/");
// Find imported module
let module_info =
environment
.importable_modules
.get(&name)
.ok_or_else(|| Error::UnknownModule {
location,
name,
imported_modules: environment.imported_modules.keys().cloned().collect(),
})?;
// TODO: remove this most likely
// Record any imports that are types only as this information is
// needed to prevent types being imported in generated JavaScript
for import in unqualified.iter_mut() {
if environment.imported_types.contains(import.variable_name()) {
import.layer = Layer::Type;
}
}
Ok(Definition::Use(Use {
location,
module,
as_name,
unqualified,
package: module_info.package.clone(),
}))
}
Definition::ModuleConstant(ModuleConstant {
doc,
location,
name,
annotation,
public,
value,
..
}) => {
if public && kind.is_validator() {
environment.warnings.push(Warning::PubInValidatorModule {
location: Span {
start: location.start,
end: location.start + PUB_OFFSET,
},
})
}
let typed_expr =
ExprTyper::new(environment, tracing).infer_const(&annotation, *value)?;
let tipo = typed_expr.tipo();
let variant = ValueConstructor {
public,
variant: ValueConstructorVariant::ModuleConstant {
location,
literal: typed_expr.clone(),
module: module_name.to_owned(),
},
tipo: tipo.clone(),
};
environment.insert_variable(name.clone(), variant.variant.clone(), tipo.clone());
environment.insert_module_value(&name, variant);
if !public {
environment.init_usage(name.clone(), EntityKind::PrivateConstant, location);
}
Ok(Definition::ModuleConstant(ModuleConstant {
doc,
location,
name,
annotation,
public,
value: Box::new(typed_expr),
tipo,
}))
}
}
}