-
-
Notifications
You must be signed in to change notification settings - Fork 477
/
builder.rs
1995 lines (1725 loc) · 72.4 KB
/
builder.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
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Semantic Builder
use std::{
cell::{Cell, RefCell},
path::PathBuf,
sync::Arc,
};
#[allow(clippy::wildcard_imports)]
use oxc_ast::{ast::*, AstKind, Trivias, Visit};
use oxc_cfg::{
ControlFlowGraphBuilder, CtxCursor, CtxFlags, EdgeType, ErrorEdgeKind,
IterationInstructionKind, ReturnInstructionKind,
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_span::{CompactStr, SourceType, Span};
use oxc_syntax::{module_record::ModuleRecord, operator::AssignmentOperator};
use crate::{
binder::Binder,
checker,
class::ClassTableBuilder,
diagnostics::redeclaration,
jsdoc::JSDocBuilder,
label::LabelBuilder,
module_record::ModuleRecordBuilder,
node::{AstNodeId, AstNodes, NodeFlags},
reference::{Reference, ReferenceFlag, ReferenceId},
scope::{ScopeFlags, ScopeId, ScopeTree, UnresolvedReferences},
symbol::{SymbolFlags, SymbolId, SymbolTable},
JSDocFinder, Semantic,
};
macro_rules! control_flow {
($self:ident, |$cfg:tt| $body:expr) => {
if let Some(ref mut $cfg) = $self.cfg {
$body
} else {
Default::default()
}
};
}
pub struct SemanticBuilder<'a> {
pub source_text: &'a str,
pub source_type: SourceType,
trivias: Trivias,
/// Semantic early errors such as redeclaration errors.
errors: RefCell<Vec<OxcDiagnostic>>,
// states
pub current_node_id: AstNodeId,
pub current_node_flags: NodeFlags,
pub current_symbol_flags: SymbolFlags,
pub current_scope_id: ScopeId,
/// Current scope depth.
/// 0 is global scope. 1 is `Program`. Incremented on entering a scope, and decremented on exit.
pub current_scope_depth: usize,
/// Stores current `AstKind::Function` and `AstKind::ArrowFunctionExpression` during AST visit
pub function_stack: Vec<AstNodeId>,
// To make a namespace/module value like
// we need the to know the modules we are inside
// and when we reach a value declaration we set it
// to value like
pub namespace_stack: Vec<SymbolId>,
current_reference_flag: ReferenceFlag,
// builders
pub nodes: AstNodes<'a>,
pub scope: ScopeTree,
pub symbols: SymbolTable,
// Stack used to accumulate unresolved refs while traversing scopes.
// Indexed by scope depth. We recycle `UnresolvedReferences` instances during traversal
// to reduce allocations, so the stack grows to maximum scope depth, but never shrinks.
// See: <https://github.com/oxc-project/oxc/issues/4169>
unresolved_references: Vec<UnresolvedReferences>,
pub(crate) module_record: Arc<ModuleRecord>,
pub label_builder: LabelBuilder<'a>,
build_jsdoc: bool,
jsdoc: JSDocBuilder<'a>,
check_syntax_error: bool,
pub cfg: Option<ControlFlowGraphBuilder<'a>>,
pub class_table_builder: ClassTableBuilder,
ast_node_records: Vec<AstNodeId>,
}
pub struct SemanticBuilderReturn<'a> {
pub semantic: Semantic<'a>,
pub errors: Vec<OxcDiagnostic>,
}
#[derive(Default, Debug)]
pub struct Collector {
node: usize,
scope: usize,
symbol: usize,
reference: usize,
}
impl<'a> Visit<'a> for Collector {
#[inline]
fn enter_node(&mut self, _: AstKind<'a>) {
self.node += 1;
}
#[inline]
fn enter_scope(&mut self, _: ScopeFlags, _: &Cell<Option<ScopeId>>) {
self.scope += 1;
}
#[inline]
fn visit_binding_identifier(&mut self, _: &BindingIdentifier<'a>) {
self.symbol += 1;
self.node += 1;
}
#[inline]
fn visit_identifier_reference(&mut self, _: &IdentifierReference<'a>) {
self.reference += 1;
self.node += 1;
}
#[inline]
fn visit_jsx_identifier(&mut self, _: &JSXIdentifier<'a>) {
self.reference += 1;
self.node += 1;
}
#[inline]
fn visit_jsx_member_expression_object(&mut self, it: &JSXMemberExpressionObject<'a>) {
self.node += 1;
if let JSXMemberExpressionObject::MemberExpression(expr) = &it {
self.visit_jsx_member_expression(expr);
} else {
self.node += 1;
}
}
#[inline]
fn visit_jsx_element_name(&mut self, it: &JSXElementName<'a>) {
self.node += 1;
if let JSXElementName::Identifier(ident) = it {
self.node += 1;
if ident.name.chars().next().is_some_and(char::is_uppercase) {
self.reference += 1;
}
} else {
self.visit_jsx_element_name(it);
}
}
#[inline]
fn visit_jsx_attribute_name(&mut self, it: &JSXAttributeName<'a>) {
// NOTE: AstKind doesn't exists!
// self.node += 1;
if let JSXAttributeName::Identifier(_) = it {
self.node += 1;
} else {
self.visit_jsx_attribute_name(it);
}
}
}
impl<'a> SemanticBuilder<'a> {
pub fn new(source_text: &'a str, source_type: SourceType) -> Self {
let scope = ScopeTree::default();
let current_scope_id = scope.root_scope_id();
// Most programs will have at least 1 place where scope depth reaches 16,
// so initialize `unresolved_references` with this length, to reduce reallocations as it grows.
// This is just an estimate of a good initial size, but certainly better than
// `Vec`'s default initial capacity of 4.
let mut unresolved_references = vec![];
unresolved_references.resize_with(16, Default::default);
let trivias = Trivias::default();
Self {
source_text,
source_type,
trivias: trivias.clone(),
errors: RefCell::new(vec![]),
current_node_id: AstNodeId::new(0),
current_node_flags: NodeFlags::empty(),
current_symbol_flags: SymbolFlags::empty(),
current_reference_flag: ReferenceFlag::empty(),
current_scope_id,
current_scope_depth: 0,
function_stack: vec![],
namespace_stack: vec![],
nodes: AstNodes::default(),
scope,
symbols: SymbolTable::default(),
unresolved_references,
module_record: Arc::new(ModuleRecord::default()),
label_builder: LabelBuilder::default(),
build_jsdoc: false,
jsdoc: JSDocBuilder::new(source_text, trivias),
check_syntax_error: false,
cfg: None,
class_table_builder: ClassTableBuilder::new(),
ast_node_records: Vec::new(),
}
}
#[must_use]
pub fn with_trivias(mut self, trivias: Trivias) -> Self {
self.trivias = trivias.clone();
self.jsdoc = JSDocBuilder::new(self.source_text, trivias);
self
}
#[must_use]
pub fn with_check_syntax_error(mut self, yes: bool) -> Self {
self.check_syntax_error = yes;
self
}
#[must_use]
pub fn with_build_jsdoc(mut self, yes: bool) -> Self {
self.build_jsdoc = yes;
self
}
#[must_use]
pub fn with_cfg(mut self, cfg: bool) -> Self {
self.cfg = if cfg { Some(ControlFlowGraphBuilder::default()) } else { None };
self
}
/// Get the built module record from `build_module_record`
pub fn module_record(&self) -> Arc<ModuleRecord> {
Arc::clone(&self.module_record)
}
/// Build the module record with a shallow AST visit
#[must_use]
pub fn build_module_record(
mut self,
resolved_absolute_path: PathBuf,
program: &Program<'a>,
) -> Self {
let mut module_record_builder = ModuleRecordBuilder::new(resolved_absolute_path);
module_record_builder.visit(program);
self.module_record = Arc::new(module_record_builder.build());
self
}
/// Finalize the builder.
///
/// # Panics
pub fn build(mut self, program: &Program<'a>) -> SemanticBuilderReturn<'a> {
if self.source_type.is_typescript_definition() {
let scope_id = self.scope.add_scope(None, AstNodeId::DUMMY, ScopeFlags::Top);
program.scope_id.set(Some(scope_id));
} else {
let mut collector = Collector::default();
collector.visit_program(program);
self.nodes.reserve(collector.node);
self.scope.reserve(collector.scope);
self.symbols.reserve(collector.symbol, collector.reference);
self.visit_program(program);
// Checking syntax error on module record requires scope information from the previous AST pass
if self.check_syntax_error {
checker::check_module_record(&self);
}
}
debug_assert_eq!(self.current_scope_depth, 0);
self.scope.root_unresolved_references =
self.unresolved_references.into_iter().next().unwrap();
let jsdoc = if self.build_jsdoc { self.jsdoc.build() } else { JSDocFinder::default() };
let semantic = Semantic {
source_text: self.source_text,
source_type: self.source_type,
trivias: self.trivias,
nodes: self.nodes,
scopes: self.scope,
symbols: self.symbols,
classes: self.class_table_builder.build(),
module_record: Arc::clone(&self.module_record),
jsdoc,
unused_labels: self.label_builder.unused_node_ids,
cfg: self.cfg.map(ControlFlowGraphBuilder::build),
};
SemanticBuilderReturn { semantic, errors: self.errors.into_inner() }
}
/// Push a Syntax Error
pub fn error(&self, error: OxcDiagnostic) {
self.errors.borrow_mut().push(error);
}
fn create_ast_node(&mut self, kind: AstKind<'a>) {
let mut flags = self.current_node_flags;
if self.build_jsdoc && self.jsdoc.retrieve_attached_jsdoc(&kind) {
flags |= NodeFlags::JSDoc;
}
self.current_node_id = self.nodes.add_node(
kind,
self.current_scope_id,
self.current_node_id,
control_flow!(self, |cfg| cfg.current_node_ix),
flags,
);
self.record_ast_node();
}
fn pop_ast_node(&mut self) {
if let Some(parent_id) = self.nodes.parent_id(self.current_node_id) {
self.current_node_id = parent_id;
}
}
#[inline]
fn record_ast_nodes(&mut self) {
if self.cfg.is_some() {
self.ast_node_records.push(AstNodeId::DUMMY);
}
}
#[inline]
#[allow(clippy::unnecessary_wraps)]
fn retrieve_recorded_ast_node(&mut self) -> Option<AstNodeId> {
if self.cfg.is_some() {
Some(self.ast_node_records.pop().expect("there is no ast node record to stop."))
} else {
None
}
}
#[inline]
fn record_ast_node(&mut self) {
// The `self.cfg.is_some()` check here could be removed, since `ast_node_records` is empty
// if CFG is disabled. But benchmarks showed removing the extra check is a perf regression.
// <https://github.com/oxc-project/oxc/pull/4273>
if self.cfg.is_some() {
if let Some(record) = self.ast_node_records.last_mut() {
if *record == AstNodeId::DUMMY {
*record = self.current_node_id;
}
}
}
}
pub fn current_scope_flags(&self) -> ScopeFlags {
self.scope.get_flags(self.current_scope_id)
}
pub fn strict_mode(&self) -> bool {
self.current_scope_flags().is_strict_mode()
}
pub fn set_function_node_flag(&mut self, flag: NodeFlags) {
if let Some(current_function) = self.function_stack.last() {
*self.nodes.get_node_mut(*current_function).flags_mut() |= flag;
}
}
/// Declares a `Symbol` for the node, adds it to symbol table, and binds it to the scope.
///
/// includes: the `SymbolFlags` that node has in addition to its declaration type (eg: export, ambient, etc.)
/// excludes: the flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
///
/// Reports errors for conflicting identifier names.
pub fn declare_symbol_on_scope(
&mut self,
span: Span,
name: &str,
scope_id: ScopeId,
includes: SymbolFlags,
excludes: SymbolFlags,
) -> SymbolId {
if let Some(symbol_id) = self.check_redeclaration(scope_id, span, name, excludes, true) {
self.symbols.union_flag(symbol_id, includes);
self.add_redeclare_variable(symbol_id, span);
return symbol_id;
}
let includes = includes | self.current_symbol_flags;
let name = CompactStr::new(name);
let symbol_id = self.symbols.create_symbol(span, name.clone(), includes, scope_id);
self.symbols.add_declaration(self.current_node_id);
self.scope.add_binding(scope_id, name, symbol_id);
symbol_id
}
pub fn declare_symbol(
&mut self,
span: Span,
name: &str,
includes: SymbolFlags,
excludes: SymbolFlags,
) -> SymbolId {
self.declare_symbol_on_scope(span, name, self.current_scope_id, includes, excludes)
}
pub fn check_redeclaration(
&mut self,
scope_id: ScopeId,
span: Span,
name: &str,
excludes: SymbolFlags,
report_error: bool,
) -> Option<SymbolId> {
let symbol_id = self.scope.get_binding(scope_id, name)?;
if report_error && self.symbols.get_flag(symbol_id).intersects(excludes) {
let symbol_span = self.symbols.get_span(symbol_id);
self.error(redeclaration(name, symbol_span, span));
}
Some(symbol_id)
}
/// Declare an unresolved reference in the current scope.
///
/// # Panics
pub fn declare_reference(&mut self, reference: Reference) -> ReferenceId {
let reference_name = reference.name().clone();
let reference_flag = *reference.flag();
let reference_id = self.symbols.create_reference(reference);
self.unresolved_references[self.current_scope_depth]
.entry(reference_name)
.or_default()
.push((reference_id, reference_flag));
reference_id
}
/// Declares a `Symbol` for the node, shadowing previous declarations in the same scope.
pub fn declare_shadow_symbol(
&mut self,
name: &str,
span: Span,
scope_id: ScopeId,
includes: SymbolFlags,
) -> SymbolId {
let includes = includes | self.current_symbol_flags;
let name = CompactStr::new(name);
let symbol_id =
self.symbols.create_symbol(span, name.clone(), includes, self.current_scope_id);
self.symbols.add_declaration(self.current_node_id);
self.scope.get_bindings_mut(scope_id).insert(name, symbol_id);
symbol_id
}
fn resolve_references_for_current_scope(&mut self) {
// `iter_mut` to get mut references to 2 entries of `unresolved_references` simultaneously
let mut iter = self.unresolved_references.iter_mut();
let parent_refs = iter.nth(self.current_scope_depth - 1).unwrap();
let current_refs = iter.next().unwrap();
for (name, mut references) in current_refs.drain() {
// Try to resolve a reference.
// If unresolved, transfer it to parent scope's unresolved references.
let bindings = self.scope.get_bindings(self.current_scope_id);
if let Some(symbol_id) = bindings.get(&name).copied() {
let symbol_flag = self.symbols.get_flag(symbol_id);
let resolved_references: &mut Vec<_> =
self.symbols.resolved_references[symbol_id].as_mut();
// Reserve space for all references to avoid reallocations.
resolved_references.reserve(references.len());
references.retain(|(id, flag)| {
if flag.is_type() && symbol_flag.can_be_referenced_by_type()
|| flag.is_value() && symbol_flag.can_be_referenced_by_value()
{
// The non type-only ExportSpecifier can reference a type/value symbol,
// If the symbol is a value symbol and reference flag is not type-only, remove the type flag.
if symbol_flag.is_value() && !flag.is_type_only() {
*self.symbols.references[*id].flag_mut() -= ReferenceFlag::Type;
}
self.symbols.references[*id].set_symbol_id(symbol_id);
resolved_references.push(*id);
false
} else {
true
}
});
if references.is_empty() {
continue;
}
}
if let Some(parent_reference_ids) = parent_refs.get_mut(&name) {
parent_reference_ids.extend(references);
} else {
parent_refs.insert(name, references);
}
}
}
pub fn add_redeclare_variable(&mut self, symbol_id: SymbolId, span: Span) {
self.symbols.add_redeclare_variable(symbol_id, span);
}
fn add_export_flag_to_export_identifiers(&mut self, program: &Program<'a>) {
for stmt in &program.body {
if let Statement::ExportDefaultDeclaration(decl) = stmt {
if let ExportDefaultDeclarationKind::Identifier(ident) = &decl.declaration {
self.add_export_flag_to_identifier(ident.name.as_str());
}
}
if let Statement::ExportNamedDeclaration(decl) = stmt {
for specifier in &decl.specifiers {
if specifier.export_kind.is_value() {
if let Some(name) = specifier.local.identifier_name() {
self.add_export_flag_to_identifier(name.as_str());
}
}
}
}
}
}
fn add_export_flag_to_identifier(&mut self, name: &str) {
if let Some(symbol_id) = self.scope.get_binding(self.current_scope_id, name) {
self.symbols.union_flag(symbol_id, SymbolFlags::Export);
}
}
}
impl<'a> Visit<'a> for SemanticBuilder<'a> {
fn enter_scope(&mut self, flags: ScopeFlags, scope_id: &Cell<Option<ScopeId>>) {
let parent_scope_id =
if flags.contains(ScopeFlags::Top) { None } else { Some(self.current_scope_id) };
let mut flags = flags;
if !flags.is_strict_mode() && self.current_node_flags.has_class() {
// NOTE A class definition is always strict mode code.
flags |= ScopeFlags::StrictMode;
};
if let Some(parent_scope_id) = parent_scope_id {
flags = self.scope.get_new_scope_flags(flags, parent_scope_id);
}
self.current_scope_id = self.scope.add_scope(parent_scope_id, self.current_node_id, flags);
scope_id.set(Some(self.current_scope_id));
if let Some(parent_scope_id) = parent_scope_id {
if self.scope.get_flags(parent_scope_id).is_catch_clause() {
// Clone the `CatchClause` bindings and add them to the current scope.
// to make it easier to check redeclare errors.
let bindings = self.scope.get_bindings(parent_scope_id).clone();
self.scope.get_bindings_mut(self.current_scope_id).extend(bindings);
}
}
// Increment scope depth, and ensure stack is large enough that
// `self.unresolved_references[self.current_scope_depth]` is initialized
self.current_scope_depth += 1;
if self.unresolved_references.len() <= self.current_scope_depth {
self.unresolved_references.push(UnresolvedReferences::default());
}
}
fn leave_scope(&mut self) {
self.resolve_references_for_current_scope();
if let Some(parent_id) = self.scope.get_parent_id(self.current_scope_id) {
self.current_scope_id = parent_id;
}
self.current_scope_depth -= 1;
}
// Setup all the context for the binder.
// The order is important here.
fn enter_node(&mut self, kind: AstKind<'a>) {
self.create_ast_node(kind);
self.enter_kind(kind);
}
fn leave_node(&mut self, kind: AstKind<'a>) {
if self.check_syntax_error {
let node = self.nodes.get_node(self.current_node_id);
checker::check(node, self);
}
self.leave_kind(kind);
self.pop_ast_node();
}
fn visit_program(&mut self, program: &Program<'a>) {
let kind = AstKind::Program(self.alloc(program));
/* cfg */
let error_harness = control_flow!(self, |cfg| {
let error_harness = cfg.attach_error_harness(ErrorEdgeKind::Implicit);
let _program_basic_block = cfg.new_basic_block_normal();
error_harness
});
/* cfg - must be above directives as directives are in cfg */
self.enter_node(kind);
self.enter_scope(
{
let mut flags = ScopeFlags::Top;
if program.is_strict() {
flags |= ScopeFlags::StrictMode;
}
flags
},
&program.scope_id,
);
for directive in &program.directives {
self.visit_directive(directive);
}
self.visit_statements(&program.body);
/* cfg */
control_flow!(self, |cfg| cfg.release_error_harness(error_harness));
/* cfg */
self.leave_node(kind);
self.leave_scope();
}
fn visit_break_statement(&mut self, stmt: &BreakStatement<'a>) {
let kind = AstKind::BreakStatement(self.alloc(stmt));
self.enter_node(kind);
/* cfg */
let node_id = self.current_node_id;
/* cfg */
if let Some(ref break_target) = stmt.label {
self.visit_label_identifier(break_target);
}
/* cfg */
control_flow!(self, |cfg| cfg
.append_break(node_id, stmt.label.as_ref().map(|it| it.name.as_str())));
/* cfg */
self.leave_node(kind);
}
fn visit_class(&mut self, class: &Class<'a>) {
let kind = AstKind::Class(self.alloc(class));
self.enter_node(kind);
self.visit_decorators(&class.decorators);
if let Some(id) = &class.id {
self.visit_binding_identifier(id);
}
self.enter_scope(ScopeFlags::StrictMode, &class.scope_id);
if class.is_expression() {
// We need to bind class expression in the class scope
class.bind(self);
}
if let Some(type_parameters) = &class.type_parameters {
self.visit_ts_type_parameter_declaration(type_parameters);
}
if let Some(super_class) = &class.super_class {
self.visit_class_heritage(super_class);
}
if let Some(super_type_parameters) = &class.super_type_parameters {
self.visit_ts_type_parameter_instantiation(super_type_parameters);
}
if let Some(implements) = &class.implements {
self.visit_ts_class_implementses(implements);
}
self.visit_class_body(&class.body);
self.leave_scope();
self.leave_node(kind);
}
fn visit_continue_statement(&mut self, stmt: &ContinueStatement<'a>) {
let kind = AstKind::ContinueStatement(self.alloc(stmt));
self.enter_node(kind);
/* cfg */
let node_id = self.current_node_id;
/* cfg */
if let Some(continue_target) = &stmt.label {
self.visit_label_identifier(continue_target);
}
/* cfg */
control_flow!(self, |cfg| cfg
.append_continue(node_id, stmt.label.as_ref().map(|it| it.name.as_str())));
/* cfg */
self.leave_node(kind);
}
fn visit_do_while_statement(&mut self, stmt: &DoWhileStatement<'a>) {
let kind = AstKind::DoWhileStatement(self.alloc(stmt));
self.enter_node(kind);
/* cfg */
let (before_do_while_stmt_graph_ix, start_body_graph_ix) = control_flow!(self, |cfg| {
let before_do_while_stmt_graph_ix = cfg.current_node_ix;
let start_body_graph_ix = cfg.new_basic_block_normal();
cfg.ctx(None).default().allow_break().allow_continue();
(before_do_while_stmt_graph_ix, start_body_graph_ix)
});
/* cfg */
self.visit_statement(&stmt.body);
/* cfg - condition basic block */
let (after_body_graph_ix, start_of_condition_graph_ix) = control_flow!(self, |cfg| {
let after_body_graph_ix = cfg.current_node_ix;
let start_of_condition_graph_ix = cfg.new_basic_block_normal();
(after_body_graph_ix, start_of_condition_graph_ix)
});
/* cfg */
self.record_ast_nodes();
self.visit_expression(&stmt.test);
let test_node = self.retrieve_recorded_ast_node();
/* cfg */
control_flow!(self, |cfg| {
cfg.append_condition_to(start_of_condition_graph_ix, test_node);
let end_of_condition_graph_ix = cfg.current_node_ix;
let end_do_while_graph_ix = cfg.new_basic_block_normal();
// before do while to start of body basic block
cfg.add_edge(before_do_while_stmt_graph_ix, start_body_graph_ix, EdgeType::Normal);
// body of do-while to start of condition
cfg.add_edge(after_body_graph_ix, start_of_condition_graph_ix, EdgeType::Normal);
// end of condition to after do while
cfg.add_edge(end_of_condition_graph_ix, end_do_while_graph_ix, EdgeType::Normal);
// end of condition to after start of body
cfg.add_edge(end_of_condition_graph_ix, start_body_graph_ix, EdgeType::Backedge);
cfg.ctx(None)
.mark_break(end_do_while_graph_ix)
.mark_continue(start_of_condition_graph_ix)
.resolve_with_upper_label();
});
/* cfg */
self.leave_node(kind);
}
fn visit_logical_expression(&mut self, expr: &LogicalExpression<'a>) {
// logical expressions are short-circuiting, and therefore
// also represent control flow.
// For example, in:
// foo && bar();
// the bar() call will only be executed if foo is truthy.
let kind = AstKind::LogicalExpression(self.alloc(expr));
self.enter_node(kind);
self.visit_expression(&expr.left);
/* cfg */
let (left_expr_end_ix, right_expr_start_ix) = control_flow!(self, |cfg| {
let left_expr_end_ix = cfg.current_node_ix;
let right_expr_start_ix = cfg.new_basic_block_normal();
(left_expr_end_ix, right_expr_start_ix)
});
/* cfg */
self.visit_expression(&expr.right);
/* cfg */
control_flow!(self, |cfg| {
let right_expr_end_ix = cfg.current_node_ix;
let after_logical_expr_ix = cfg.new_basic_block_normal();
cfg.add_edge(left_expr_end_ix, right_expr_start_ix, EdgeType::Normal);
cfg.add_edge(left_expr_end_ix, after_logical_expr_ix, EdgeType::Normal);
cfg.add_edge(right_expr_end_ix, after_logical_expr_ix, EdgeType::Normal);
});
/* cfg */
self.leave_node(kind);
}
fn visit_assignment_expression(&mut self, expr: &AssignmentExpression<'a>) {
// assignment expressions can include an operator, which
// can be used to determine the control flow of the expression.
// For example, in:
// foo &&= super();
// the super() call will only be executed if foo is truthy.
let kind = AstKind::AssignmentExpression(self.alloc(expr));
self.enter_node(kind);
self.visit_assignment_target(&expr.left);
/* cfg */
let cfg_ixs = control_flow!(self, |cfg| {
if expr.operator.is_logical() {
let target_end_ix = cfg.current_node_ix;
let expr_start_ix = cfg.new_basic_block_normal();
Some((target_end_ix, expr_start_ix))
} else {
None
}
});
/* cfg */
self.visit_expression(&expr.right);
/* cfg */
control_flow!(self, |cfg| {
if let Some((target_end_ix, expr_start_ix)) = cfg_ixs {
let expr_end_ix = cfg.current_node_ix;
let after_assignment_ix = cfg.new_basic_block_normal();
cfg.add_edge(target_end_ix, expr_start_ix, EdgeType::Normal);
cfg.add_edge(target_end_ix, after_assignment_ix, EdgeType::Normal);
cfg.add_edge(expr_end_ix, after_assignment_ix, EdgeType::Normal);
}
});
/* cfg */
self.leave_node(kind);
}
fn visit_conditional_expression(&mut self, expr: &ConditionalExpression<'a>) {
let kind = AstKind::ConditionalExpression(self.alloc(expr));
self.enter_node(kind);
/* cfg - condition basic block */
let (before_conditional_graph_ix, start_of_condition_graph_ix) =
control_flow!(self, |cfg| {
let before_conditional_graph_ix = cfg.current_node_ix;
let start_of_condition_graph_ix = cfg.new_basic_block_normal();
(before_conditional_graph_ix, start_of_condition_graph_ix)
});
/* cfg */
self.record_ast_nodes();
self.visit_expression(&expr.test);
let test_node = self.retrieve_recorded_ast_node();
/* cfg */
let (after_condition_graph_ix, before_consequent_expr_graph_ix) =
control_flow!(self, |cfg| {
cfg.append_condition_to(start_of_condition_graph_ix, test_node);
let after_condition_graph_ix = cfg.current_node_ix;
// conditional expression basic block
let before_consequent_expr_graph_ix = cfg.new_basic_block_normal();
(after_condition_graph_ix, before_consequent_expr_graph_ix)
});
/* cfg */
self.visit_expression(&expr.consequent);
/* cfg */
let (after_consequent_expr_graph_ix, start_alternate_graph_ix) =
control_flow!(self, |cfg| {
let after_consequent_expr_graph_ix = cfg.current_node_ix;
let start_alternate_graph_ix = cfg.new_basic_block_normal();
(after_consequent_expr_graph_ix, start_alternate_graph_ix)
});
/* cfg */
self.visit_expression(&expr.alternate);
/* cfg */
control_flow!(self, |cfg| {
let after_alternate_graph_ix = cfg.current_node_ix;
/* bb after conditional expression joins consequent and alternate */
let after_conditional_graph_ix = cfg.new_basic_block_normal();
cfg.add_edge(
before_conditional_graph_ix,
start_of_condition_graph_ix,
EdgeType::Normal,
);
cfg.add_edge(
after_consequent_expr_graph_ix,
after_conditional_graph_ix,
EdgeType::Normal,
);
cfg.add_edge(after_condition_graph_ix, before_consequent_expr_graph_ix, EdgeType::Jump);
cfg.add_edge(after_condition_graph_ix, start_alternate_graph_ix, EdgeType::Normal);
cfg.add_edge(after_alternate_graph_ix, after_conditional_graph_ix, EdgeType::Normal);
});
/* cfg */
self.leave_node(kind);
}
fn visit_for_statement(&mut self, stmt: &ForStatement<'a>) {
let kind = AstKind::ForStatement(self.alloc(stmt));
self.enter_node(kind);
let is_lexical_declaration =
stmt.init.as_ref().is_some_and(ForStatementInit::is_lexical_declaration);
if is_lexical_declaration {
self.enter_scope(ScopeFlags::empty(), &stmt.scope_id);
}
if let Some(init) = &stmt.init {
self.visit_for_statement_init(init);
}
/* cfg */
let (before_for_graph_ix, test_graph_ix) = control_flow!(self, |cfg| {
let before_for_graph_ix = cfg.current_node_ix;
let test_graph_ix = cfg.new_basic_block_normal();
(before_for_graph_ix, test_graph_ix)
});
/* cfg */
if let Some(test) = &stmt.test {
self.record_ast_nodes();
self.visit_expression(test);
let test_node = self.retrieve_recorded_ast_node();
/* cfg */
control_flow!(self, |cfg| cfg.append_condition_to(test_graph_ix, test_node));
/* cfg */
}
/* cfg */
let (after_test_graph_ix, update_graph_ix) =
control_flow!(self, |cfg| (cfg.current_node_ix, cfg.new_basic_block_normal()));
/* cfg */
if let Some(update) = &stmt.update {
self.visit_expression(update);
}
/* cfg */
let before_body_graph_ix = control_flow!(self, |cfg| {
let before_body_graph_ix = cfg.new_basic_block_normal();
cfg.ctx(None).default().allow_break().allow_continue();
before_body_graph_ix
});
/* cfg */
self.visit_statement(&stmt.body);
/* cfg */
control_flow!(self, |cfg| {
let after_body_graph_ix = cfg.current_node_ix;
let after_for_stmt = cfg.new_basic_block_normal();
cfg.add_edge(before_for_graph_ix, test_graph_ix, EdgeType::Normal);
cfg.add_edge(after_test_graph_ix, before_body_graph_ix, EdgeType::Jump);
cfg.add_edge(after_body_graph_ix, update_graph_ix, EdgeType::Backedge);
cfg.add_edge(update_graph_ix, test_graph_ix, EdgeType::Backedge);
cfg.add_edge(after_test_graph_ix, after_for_stmt, EdgeType::Normal);
cfg.ctx(None)
.mark_break(after_for_stmt)
.mark_continue(update_graph_ix)
.resolve_with_upper_label();
});
/* cfg */
if is_lexical_declaration {
self.leave_scope();
}
self.leave_node(kind);
}
fn visit_for_in_statement(&mut self, stmt: &ForInStatement<'a>) {
let kind = AstKind::ForInStatement(self.alloc(stmt));
self.enter_node(kind);
let is_lexical_declaration = stmt.left.is_lexical_declaration();
if is_lexical_declaration {
self.enter_scope(ScopeFlags::empty(), &stmt.scope_id);
}
self.visit_for_statement_left(&stmt.left);
/* cfg */
let (before_for_stmt_graph_ix, start_prepare_cond_graph_ix) =
control_flow!(self, |cfg| (cfg.current_node_ix, cfg.new_basic_block_normal(),));
/* cfg */
self.record_ast_nodes();
self.visit_expression(&stmt.right);
let right_node = self.retrieve_recorded_ast_node();
/* cfg */
let (end_of_prepare_cond_graph_ix, iteration_graph_ix, body_graph_ix) =
control_flow!(self, |cfg| {
let end_of_prepare_cond_graph_ix = cfg.current_node_ix;
let iteration_graph_ix = cfg.new_basic_block_normal();
cfg.append_iteration(right_node, IterationInstructionKind::In);