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
use crate::{
engine_threading::Engines,
error::*,
language::{
parsed::*,
ty::{self, TyDecl},
},
semantic_analysis::*,
transform::to_parsed_lang,
Ident, Namespace,
};
use super::{
items::{GlobImport, Items, SymbolMap},
root::Root,
trait_map::TraitMap,
ModuleName, Path,
};
use sway_ast::ItemConst;
use sway_error::handler::Handler;
use sway_error::{error::CompileError, handler::ErrorEmitted};
use sway_parse::{lex, Parser};
use sway_types::{span::Span, Spanned};
#[derive(Clone, Debug, Default)]
pub struct Module {
pub(crate) submodules: im::OrdMap<ModuleName, Module>,
items: Items,
pub name: Option<Ident>,
pub span: Option<Span>,
pub is_external: bool,
}
impl Module {
pub fn default_with_contract_id(
engines: Engines<'_>,
name: Option<Ident>,
contract_id_value: String,
) -> Result<Self, vec1::Vec1<CompileError>> {
let handler = <_>::default();
Module::default_with_contract_id_inner(&handler, engines, name, contract_id_value).map_err(
|_| {
let (errors, warnings) = handler.consume();
assert!(warnings.is_empty());
vec1::Vec1::try_from_vec(errors).unwrap()
},
)
}
fn default_with_contract_id_inner(
handler: &Handler,
engines: Engines<'_>,
ns_name: Option<Ident>,
contract_id_value: String,
) -> Result<Self, ErrorEmitted> {
let mut compiled_constants: SymbolMap = Default::default();
let const_item = format!("pub const CONTRACT_ID: b256 = {contract_id_value};");
let const_item_len = const_item.len();
let input_arc = std::sync::Arc::from(const_item);
let token_stream = lex(handler, &input_arc, 0, const_item_len, None).unwrap();
let mut parser = Parser::new(handler, &token_stream);
let const_item: ItemConst = parser.parse()?;
let const_item_span = const_item.span();
let name = const_item.name.clone();
let attributes = Default::default();
let const_decl = to_parsed_lang::item_const_to_constant_declaration(
&mut to_parsed_lang::Context::default(),
handler,
engines,
const_item,
attributes,
true,
)?;
let has_literal = match &const_decl.value {
Some(value) => {
matches!(value.kind, ExpressionKind::Literal(_))
}
None => false,
};
if !has_literal {
return Err(handler.emit_err(CompileError::ContractIdValueNotALiteral {
span: const_item_span,
}));
}
let ast_node = AstNode {
content: AstNodeContent::Declaration(Declaration::ConstantDeclaration(const_decl)),
span: const_item_span.clone(),
};
let mut ns = Namespace::init_root(Default::default());
ns.root.module.name = ns_name;
ns.root.module.is_external = true;
let type_check_ctx = TypeCheckContext::from_root(&mut ns, engines);
let typed_node =
ty::TyAstNode::type_check(type_check_ctx, ast_node).unwrap(&mut vec![], &mut vec![]);
let typed_decl = match typed_node.content {
ty::TyAstNodeContent::Declaration(decl) => decl,
_ => {
return Err(
handler.emit_err(CompileError::ContractIdConstantNotAConstDecl {
span: const_item_span,
}),
);
}
};
compiled_constants.insert(name, typed_decl);
let mut ret = Self::default();
ret.items.symbols = compiled_constants;
Ok(ret)
}
pub fn submodules(&self) -> &im::OrdMap<ModuleName, Module> {
&self.submodules
}
pub fn insert_submodule(&mut self, name: String, submodule: Module) {
self.submodules.insert(name, submodule);
}
pub fn submodule(&self, path: &Path) -> Option<&Module> {
let mut module = self;
for ident in path.iter() {
match module.submodules.get(ident.as_str()) {
Some(ns) => module = ns,
None => return None,
}
}
Some(module)
}
pub fn submodule_mut(&mut self, path: &Path) -> Option<&mut Module> {
let mut module = self;
for ident in path.iter() {
match module.submodules.get_mut(ident.as_str()) {
Some(ns) => module = ns,
None => return None,
}
}
Some(module)
}
pub(crate) fn check_submodule(&self, path: &[Ident]) -> CompileResult<&Module> {
match self.submodule(path) {
None => err(vec![], vec![module_not_found(path)]),
Some(module) => ok(module, vec![], vec![]),
}
}
pub(crate) fn star_import(
&mut self,
src: &Path,
dst: &Path,
engines: Engines<'_>,
) -> CompileResult<()> {
let mut warnings = vec![];
let mut errors = vec![];
let decl_engine = engines.de();
let src_ns = check!(
self.check_submodule(src),
return err(warnings, errors),
warnings,
errors
);
let implemented_traits = src_ns.implemented_traits.clone();
let mut symbols_and_decls = vec![];
for (symbol, decl) in src_ns.symbols.iter() {
if decl.visibility(decl_engine).is_public() {
symbols_and_decls.push((symbol.clone(), decl.clone()));
}
}
let dst_ns = &mut self[dst];
dst_ns
.implemented_traits
.extend(implemented_traits, engines);
for symbol_and_decl in symbols_and_decls {
dst_ns.use_synonyms.insert(
symbol_and_decl.0,
(src.to_vec(), GlobImport::Yes, symbol_and_decl.1),
);
}
ok((), warnings, errors)
}
pub fn star_import_with_reexports(
&mut self,
src: &Path,
dst: &Path,
engines: Engines<'_>,
) -> CompileResult<()> {
let mut warnings = vec![];
let mut errors = vec![];
let decl_engine = engines.de();
let src_ns = check!(
self.check_submodule(src),
return err(warnings, errors),
warnings,
errors
);
let implemented_traits = src_ns.implemented_traits.clone();
let use_synonyms = src_ns.use_synonyms.clone();
let mut symbols_and_decls = src_ns
.use_synonyms
.iter()
.map(|(symbol, (_, _, decl))| (symbol.clone(), decl.clone()))
.collect::<Vec<_>>();
for (symbol, decl) in src_ns.symbols.iter() {
if decl.visibility(decl_engine).is_public() {
symbols_and_decls.push((symbol.clone(), decl.clone()));
}
}
let dst_ns = &mut self[dst];
dst_ns
.implemented_traits
.extend(implemented_traits, engines);
let mut try_add = |symbol, path, decl: ty::TyDecl| {
dst_ns
.use_synonyms
.insert(symbol, (path, GlobImport::Yes, decl));
};
for symbol_and_decl in symbols_and_decls {
try_add(symbol_and_decl.0, src.to_vec(), symbol_and_decl.1);
}
for (symbol, (mod_path, _, decl)) in use_synonyms {
let mut src = src[..1].to_vec();
src.extend(mod_path);
try_add(symbol, src, decl);
}
ok((), warnings, errors)
}
pub(crate) fn self_import(
&mut self,
engines: Engines<'_>,
src: &Path,
dst: &Path,
alias: Option<Ident>,
) -> CompileResult<()> {
let (last_item, src) = src.split_last().expect("guaranteed by grammar");
self.item_import(engines, src, last_item, dst, alias)
}
pub(crate) fn item_import(
&mut self,
engines: Engines<'_>,
src: &Path,
item: &Ident,
dst: &Path,
alias: Option<Ident>,
) -> CompileResult<()> {
let mut warnings = vec![];
let mut errors = vec![];
let decl_engine = engines.de();
let src_ns = check!(
self.check_submodule(src),
return err(warnings, errors),
warnings,
errors
);
let mut impls_to_insert = TraitMap::default();
match src_ns.symbols.get(item).cloned() {
Some(decl) => {
if !decl.visibility(decl_engine).is_public() {
errors.push(CompileError::ImportPrivateSymbol {
name: item.clone(),
span: item.span(),
});
}
let type_id = decl.return_type(engines).value;
if let Some(type_id) = type_id {
impls_to_insert.extend(
src_ns
.implemented_traits
.filter_by_type_item_import(type_id, engines),
engines,
);
}
let dst_ns = &mut self[dst];
let add_synonym = |name| {
if let Some((_, GlobImport::No, _)) = dst_ns.use_synonyms.get(name) {
errors.push(CompileError::ShadowsOtherSymbol { name: name.clone() });
}
dst_ns
.use_synonyms
.insert(name.clone(), (src.to_vec(), GlobImport::No, decl));
};
match alias {
Some(alias) => {
add_synonym(&alias);
dst_ns
.use_aliases
.insert(alias.as_str().to_string(), item.clone());
}
None => add_synonym(item),
};
}
None => {
errors.push(CompileError::SymbolNotFound {
name: item.clone(),
span: item.span(),
});
return err(warnings, errors);
}
};
let dst_ns = &mut self[dst];
dst_ns.implemented_traits.extend(impls_to_insert, engines);
ok((), warnings, errors)
}
pub(crate) fn variant_import(
&mut self,
engines: Engines<'_>,
src: &Path,
enum_name: &Ident,
variant_name: &Ident,
dst: &Path,
alias: Option<Ident>,
) -> CompileResult<()> {
let mut warnings = vec![];
let mut errors = vec![];
let decl_engine = engines.de();
let src_ns = check!(
self.check_submodule(src),
return err(warnings, errors),
warnings,
errors
);
match src_ns.symbols.get(enum_name).cloned() {
Some(decl) => {
if !decl.visibility(decl_engine).is_public() {
errors.push(CompileError::ImportPrivateSymbol {
name: enum_name.clone(),
span: enum_name.span(),
});
}
if let TyDecl::EnumDecl {
decl_id,
subst_list,
..
} = decl
{
let enum_decl = decl_engine.get_enum(&decl_id);
if let Some(variant_decl) =
enum_decl.variants.iter().find(|v| v.name == *variant_name)
{
let dst_ns = &mut self[dst];
let add_synonym = |name| {
if let Some((_, GlobImport::No, _)) = dst_ns.use_synonyms.get(name) {
errors
.push(CompileError::ShadowsOtherSymbol { name: name.clone() });
}
dst_ns.use_synonyms.insert(
name.clone(),
(
src.to_vec(),
GlobImport::No,
TyDecl::EnumVariantDecl {
decl_id,
subst_list,
variant_name: variant_name.clone(),
variant_decl_span: variant_decl.span.clone(),
},
),
);
};
match alias {
Some(alias) => {
add_synonym(&alias);
dst_ns
.use_aliases
.insert(alias.as_str().to_string(), variant_name.clone());
}
None => add_synonym(variant_name),
};
} else {
errors.push(CompileError::SymbolNotFound {
name: variant_name.clone(),
span: variant_name.span(),
});
return err(warnings, errors);
}
} else {
errors.push(CompileError::Internal(
"Attempting to import variants of something that isn't an enum",
enum_name.span(),
));
return err(warnings, errors);
}
}
None => {
errors.push(CompileError::SymbolNotFound {
name: enum_name.clone(),
span: enum_name.span(),
});
return err(warnings, errors);
}
};
ok((), warnings, errors)
}
pub(crate) fn variant_star_import(
&mut self,
src: &Path,
dst: &Path,
engines: Engines<'_>,
enum_name: &Ident,
) -> CompileResult<()> {
let mut warnings = vec![];
let mut errors = vec![];
let decl_engine = engines.de();
let src_ns = check!(
self.check_submodule(src),
return err(warnings, errors),
warnings,
errors
);
match src_ns.symbols.get(enum_name).cloned() {
Some(decl) => {
if !decl.visibility(decl_engine).is_public() {
errors.push(CompileError::ImportPrivateSymbol {
name: enum_name.clone(),
span: enum_name.span(),
});
}
if let TyDecl::EnumDecl {
decl_id,
subst_list,
..
} = decl
{
let enum_decl = decl_engine.get_enum(&decl_id);
for variant_decl in enum_decl.variants {
let variant_name = variant_decl.name;
let dst_ns = &mut self[dst];
dst_ns.use_synonyms.insert(
variant_name.clone(),
(
src.to_vec(),
GlobImport::Yes,
TyDecl::EnumVariantDecl {
decl_id,
subst_list: subst_list.clone(),
variant_name,
variant_decl_span: variant_decl.span.clone(),
},
),
);
}
} else {
errors.push(CompileError::Internal(
"Attempting to import variants of something that isn't an enum",
enum_name.span(),
));
return err(warnings, errors);
}
}
None => {
errors.push(CompileError::SymbolNotFound {
name: enum_name.clone(),
span: enum_name.span(),
});
return err(warnings, errors);
}
};
ok((), warnings, errors)
}
}
impl std::ops::Deref for Module {
type Target = Items;
fn deref(&self) -> &Self::Target {
&self.items
}
}
impl std::ops::DerefMut for Module {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.items
}
}
impl<'a> std::ops::Index<&'a Path> for Module {
type Output = Module;
fn index(&self, path: &'a Path) -> &Self::Output {
self.submodule(path)
.unwrap_or_else(|| panic!("no module for the given path {path:?}"))
}
}
impl<'a> std::ops::IndexMut<&'a Path> for Module {
fn index_mut(&mut self, path: &'a Path) -> &mut Self::Output {
self.submodule_mut(path)
.unwrap_or_else(|| panic!("no module for the given path {path:?}"))
}
}
impl From<Root> for Module {
fn from(root: Root) -> Self {
root.module
}
}
fn module_not_found(path: &[Ident]) -> CompileError {
CompileError::ModuleNotFound {
span: path.iter().fold(path[0].span(), |acc, this_one| {
if acc.path() == this_one.span().path() {
Span::join(acc, this_one.span())
} else {
acc
}
}),
name: path
.iter()
.map(|x| x.as_str())
.collect::<Vec<_>>()
.join("::"),
}
}