-
-
Notifications
You must be signed in to change notification settings - Fork 466
/
builder.rs
2079 lines (1807 loc) · 78.2 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::Path,
sync::Arc,
};
use rustc_hash::FxHashMap;
#[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::{Atom, CompactStr, SourceType, Span};
use oxc_syntax::{module_record::ModuleRecord, operator::AssignmentOperator};
use crate::{
binder::Binder,
checker,
class::ClassTableBuilder,
diagnostics::redeclaration,
jsdoc::JSDocBuilder,
label::UnusedLabels,
module_record::ModuleRecordBuilder,
node::{AstNodes, NodeFlags, NodeId},
reference::{Reference, ReferenceFlags, ReferenceId},
scope::{Bindings, ScopeFlags, ScopeId, ScopeTree},
stats::Stats,
symbol::{SymbolFlags, SymbolId, SymbolTable},
unresolved_stack::UnresolvedReferencesStack,
JSDocFinder, Semantic,
};
macro_rules! control_flow {
($self:ident, |$cfg:tt| $body:expr) => {
if let Some(ref mut $cfg) = $self.cfg {
$body
} else {
Default::default()
}
};
}
/// Semantic Builder
///
/// Traverses a parsed AST and builds a [`Semantic`] representation of the
/// program.
///
/// The main API is the [`build`] method.
///
/// # Example
///
/// ```rust
#[doc = include_str!("../examples/simple.rs")]
/// ```
///
/// [`build`]: SemanticBuilder::build
pub struct SemanticBuilder<'a> {
/// source code of the parsed program
pub(crate) source_text: &'a str,
/// source type of the parsed program
pub(crate) source_type: SourceType,
trivias: Trivias,
/// Semantic early errors such as redeclaration errors.
errors: RefCell<Vec<OxcDiagnostic>>,
// states
pub(crate) current_node_id: NodeId,
pub(crate) current_node_flags: NodeFlags,
pub(crate) current_symbol_flags: SymbolFlags,
pub(crate) current_scope_id: ScopeId,
/// Stores current `AstKind::Function` and `AstKind::ArrowFunctionExpression` during AST visit
pub(crate) function_stack: Vec<NodeId>,
// 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(crate) namespace_stack: Vec<Option<SymbolId>>,
current_reference_flags: ReferenceFlags,
pub(crate) hoisting_variables: FxHashMap<ScopeId, FxHashMap<Atom<'a>, SymbolId>>,
// builders
pub(crate) nodes: AstNodes<'a>,
pub(crate) scope: ScopeTree,
pub(crate) symbols: SymbolTable,
unresolved_references: UnresolvedReferencesStack<'a>,
pub(crate) module_record: Arc<ModuleRecord>,
unused_labels: UnusedLabels<'a>,
build_jsdoc: bool,
jsdoc: JSDocBuilder<'a>,
stats: Option<Stats>,
excess_capacity: f64,
/// Should additional syntax checks be performed?
///
/// See: [`crate::checker::check`]
check_syntax_error: bool,
pub(crate) cfg: Option<ControlFlowGraphBuilder<'a>>,
pub(crate) class_table_builder: ClassTableBuilder,
ast_node_records: Vec<NodeId>,
}
/// Data returned by [`SemanticBuilder::build`].
pub struct SemanticBuilderReturn<'a> {
pub semantic: Semantic<'a>,
pub errors: Vec<OxcDiagnostic>,
}
impl<'a> SemanticBuilder<'a> {
pub fn new(source_text: &'a str) -> Self {
let scope = ScopeTree::default();
let current_scope_id = scope.root_scope_id();
let trivias = Trivias::default();
Self {
source_text,
source_type: SourceType::default(),
trivias: trivias.clone(),
errors: RefCell::new(vec![]),
current_node_id: NodeId::new(0),
current_node_flags: NodeFlags::empty(),
current_symbol_flags: SymbolFlags::empty(),
current_reference_flags: ReferenceFlags::empty(),
current_scope_id,
function_stack: vec![],
namespace_stack: vec![],
nodes: AstNodes::default(),
hoisting_variables: FxHashMap::default(),
scope,
symbols: SymbolTable::default(),
unresolved_references: UnresolvedReferencesStack::new(),
module_record: Arc::new(ModuleRecord::default()),
unused_labels: UnusedLabels::default(),
build_jsdoc: false,
jsdoc: JSDocBuilder::new(source_text, &trivias),
stats: None,
excess_capacity: 0.0,
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;
self
}
/// Enable/disable additional syntax checks.
///
/// Set this to `true` to enable additional syntax checks. Without these,
/// there is no guarantee that the parsed program follows the ECMAScript
/// spec.
///
/// By default, this is `false`.
#[must_use]
pub fn with_check_syntax_error(mut self, yes: bool) -> Self {
self.check_syntax_error = yes;
self
}
/// Enable/disable JSDoc parsing.
/// `with_trivias` must be called prior to this call.
#[must_use]
pub fn with_build_jsdoc(mut self, yes: bool) -> Self {
self.jsdoc = JSDocBuilder::new(self.source_text, &self.trivias);
self.build_jsdoc = yes;
self
}
/// Enable or disable building a [`ControlFlowGraph`].
///
/// [`ControlFlowGraph`]: oxc_cfg::ControlFlowGraph
#[must_use]
pub fn with_cfg(mut self, cfg: bool) -> Self {
self.cfg = if cfg { Some(ControlFlowGraphBuilder::default()) } else { None };
self
}
#[must_use]
pub fn with_scope_tree_child_ids(mut self, yes: bool) -> Self {
self.scope.build_child_ids = yes;
self
}
/// Provide statistics about AST to optimize memory usage of semantic analysis.
///
/// Accurate statistics can greatly improve performance, especially for large ASTs.
/// If no stats are provided, [`SemanticBuilder::build`] will compile stats by performing
/// a complete AST traversal.
/// If semantic analysis has already been performed on this AST, get the existing stats with
/// [`Semantic::stats`], and pass them in with this method, to avoid the stats collection AST pass.
#[must_use]
pub fn with_stats(mut self, stats: Stats) -> Self {
self.stats = Some(stats);
self
}
/// Request `SemanticBuilder` to allocate excess capacity for scopes, symbols, and references.
///
/// `excess_capacity` is provided as a fraction.
/// e.g. to over-allocate by 20%, pass `0.2` as `excess_capacity`.
///
/// Has no effect if a `Stats` object is provided with [`SemanticBuilder::with_stats`],
/// only if `SemanticBuilder` is calculating stats itself.
///
/// This is useful when you intend to modify `Semantic`, adding more `nodes`, `scopes`, `symbols`,
/// or `references`. Allocating excess capacity for these additions at the outset prevents
/// `Semantic`'s data structures needing to grow later on which involves memory copying.
/// For large ASTs with a lot of semantic data, re-allocation can be very costly.
#[must_use]
pub fn with_excess_capacity(mut self, excess_capacity: f64) -> Self {
self.excess_capacity = excess_capacity;
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: &Path,
program: &Program<'a>,
) -> Self {
let mut module_record_builder =
ModuleRecordBuilder::new(resolved_absolute_path.to_path_buf());
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> {
self.source_type = program.source_type;
if self.source_type.is_typescript_definition() {
let scope_id = self.scope.add_scope(None, NodeId::DUMMY, ScopeFlags::Top);
program.scope_id.set(Some(scope_id));
} else {
// Use counts of nodes, scopes, symbols, and references to pre-allocate sufficient capacity
// in `AstNodes`, `ScopeTree` and `SymbolTable`.
//
// This means that as we traverse the AST and fill up these structures with data,
// they never need to grow and reallocate - which is an expensive operation as it
// involves copying all the memory from the old allocation to the new one.
// For large source files, these structures are very large, so growth is very costly
// as it involves copying massive chunks of memory.
// Avoiding this growth produces up to 30% perf boost on our benchmarks.
//
// If user did not provide existing `Stats`, calculate them by visiting AST.
#[cfg_attr(not(debug_assertions), expect(unused_variables))]
let (stats, check_stats) = if let Some(stats) = self.stats {
(stats, None)
} else {
let stats = Stats::count(program);
let stats_with_excess = stats.increase_by(self.excess_capacity);
(stats_with_excess, Some(stats))
};
self.nodes.reserve(stats.nodes as usize);
self.scope.reserve(stats.scopes as usize);
self.symbols.reserve(stats.symbols as usize, stats.references as usize);
// Visit AST to generate scopes tree etc
self.visit_program(program);
// Check that estimated counts accurately (unless in release mode)
#[cfg(debug_assertions)]
if let Some(stats) = check_stats {
#[allow(clippy::cast_possible_truncation)]
let actual_stats = Stats::new(
self.nodes.len() as u32,
self.scope.len() as u32,
self.symbols.len() as u32,
self.symbols.references.len() as u32,
);
stats.assert_accurate(actual_stats);
}
// 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.unresolved_references.scope_depth(), 1);
self.scope.root_unresolved_references = self
.unresolved_references
.into_root()
.into_iter()
.map(|(k, v)| (k.into(), v))
.collect();
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.unused_labels.labels,
cfg: self.cfg.map(ControlFlowGraphBuilder::build),
};
SemanticBuilderReturn { semantic, errors: self.errors.into_inner() }
}
/// Push a Syntax Error
pub(crate) 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(NodeId::DUMMY);
}
}
#[inline]
#[allow(clippy::unnecessary_wraps)]
fn retrieve_recorded_ast_node(&mut self) -> Option<NodeId> {
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 == NodeId::DUMMY {
*record = self.current_node_id;
}
}
}
}
#[inline]
pub(crate) fn current_scope_flags(&self) -> ScopeFlags {
self.scope.get_flags(self.current_scope_id)
}
/// Is the current scope in strict mode?
pub(crate) fn strict_mode(&self) -> bool {
self.current_scope_flags().is_strict_mode()
}
pub(crate) fn set_function_node_flags(&mut self, flags: NodeFlags) {
if let Some(current_function) = self.function_stack.last() {
*self.nodes.get_node_mut(*current_function).flags_mut() |= flags;
}
}
/// 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(crate) 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.current_node_id,
);
self.scope.add_binding(scope_id, name, symbol_id);
symbol_id
}
/// Declare a new symbol on the current scope.
pub(crate) 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)
}
/// Check if a symbol with the same name has already been declared in the
/// current scope. Returns the symbol ID if it exists and is not excluded by `excludes`.
///
/// Only records a redeclaration error if `report_error` is `true`.
pub(crate) fn check_redeclaration(
&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).or_else(|| {
self.hoisting_variables.get(&scope_id).and_then(|symbols| symbols.get(name).copied())
})?;
if report_error && self.symbols.get_flags(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(crate) fn declare_reference(
&mut self,
name: Atom<'a>,
reference: Reference,
) -> ReferenceId {
let reference_id = self.symbols.create_reference(reference);
self.unresolved_references.current_mut().entry(name).or_default().push(reference_id);
reference_id
}
/// Declares a `Symbol` for the node, shadowing previous declarations in the same scope.
pub(crate) 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.current_node_id,
);
self.scope.get_bindings_mut(scope_id).insert(name, symbol_id);
symbol_id
}
/// Try to resolve all references from the current scope that are not
/// already resolved.
///
/// This gets called every time [`SemanticBuilder`] exits a scope.
fn resolve_references_for_current_scope(&mut self) {
let (current_refs, parent_refs) = self.unresolved_references.current_and_parent_mut();
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.as_str()).copied() {
let symbol_flags = self.symbols.get_flags(symbol_id);
let resolved_references = &mut self.symbols.resolved_references[symbol_id];
references.retain(|&reference_id| {
let reference = &mut self.symbols.references[reference_id];
let flags = reference.flags();
if flags.is_type() && symbol_flags.can_be_referenced_by_type()
|| flags.is_value() && symbol_flags.can_be_referenced_by_value()
|| flags.is_value_as_type()
&& (symbol_flags.can_be_referenced_by_value()
|| symbol_flags.is_type_import())
{
if flags.is_value_as_type() {
// Resolve pending type references (e.g., from `typeof` expressions) to proper type references.
*reference.flags_mut() = ReferenceFlags::Type;
} else if symbol_flags.is_value() && !flags.is_type_only() {
// 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.
*reference.flags_mut() -= ReferenceFlags::Type;
} else {
// If the symbol is a type symbol and reference flag is not type-only, remove the value flag.
*reference.flags_mut() -= ReferenceFlags::Value;
}
reference.set_symbol_id(symbol_id);
resolved_references.push(reference_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(crate) fn add_redeclare_variable(&mut self, symbol_id: SymbolId, span: Span) {
self.symbols.add_redeclaration(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());
}
}
}
}
}
}
/// Flag the symbol bound to an identifier in the current scope as exported.
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> {
// NB: Not called for `Program`
fn enter_scope(&mut self, flags: ScopeFlags, scope_id: &Cell<Option<ScopeId>>) {
let parent_scope_id = self.current_scope_id;
let flags = self.scope.get_new_scope_flags(flags, parent_scope_id);
self.current_scope_id =
self.scope.add_scope(Some(parent_scope_id), self.current_node_id, flags);
scope_id.set(Some(self.current_scope_id));
self.unresolved_references.increment_scope_depth();
}
// NB: Not called for `Program`
fn leave_scope(&mut self) {
self.resolve_references_for_current_scope();
// `get_parent_id` always returns `Some` because this method is not called for `Program`.
// So we could `.unwrap()` here. But that seems to produce a small perf impact, probably because
// `leave_scope` then doesn't get inlined because of its larger size due to the panic code.
let parent_id = self.scope.get_parent_id(self.current_scope_id);
debug_assert!(parent_id.is_some());
if let Some(parent_id) = parent_id {
self.current_scope_id = parent_id;
}
self.unresolved_references.decrement_scope_depth();
}
// Setup all the context for the binder.
// The order is important here.
// NB: Not called for `Program`.
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 */
// Don't call `enter_node` here as `Program` is a special case - node has no `parent_id`.
// Inline the specific logic for `Program` here instead.
// This avoids `Nodes::add_node` having to handle the special case.
// We can also skip calling `self.enter_kind`, `self.record_ast_node`
// and `self.jsdoc.retrieve_attached_jsdoc`, as they are all no-ops for `Program`.
self.current_node_id = self.nodes.add_program_node(
kind,
self.current_scope_id,
control_flow!(self, |cfg| cfg.current_node_ix),
self.current_node_flags,
);
// Don't call `enter_scope` here as `Program` is a special case - scope has no `parent_id`.
// Inline the specific logic for `Program` here instead.
// This simplifies logic in `enter_scope`, as it doesn't have to handle the special case.
let mut flags = ScopeFlags::Top;
if program.is_strict() {
flags |= ScopeFlags::StrictMode;
}
self.current_scope_id = self.scope.add_scope(None, self.current_node_id, flags);
program.scope_id.set(Some(self.current_scope_id));
// NB: Don't call `self.unresolved_references.increment_scope_depth()`
// as scope depth is initialized as 1 already (the scope depth for `Program`).
if let Some(hashbang) = &program.hashbang {
self.visit_hashbang(hashbang);
}
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 */
// Don't call `leave_scope` here as `Program` is a special case - scope has no `parent_id`.
// This simplifies `leave_scope`.
self.resolve_references_for_current_scope();
// NB: Don't call `self.unresolved_references.decrement_scope_depth()`
// as scope depth must remain >= 1.
self.leave_node(kind);
}
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(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_block_statement(&mut self, it: &BlockStatement<'a>) {
let kind = AstKind::BlockStatement(self.alloc(it));
self.enter_node(kind);
let parent_scope_id = self.current_scope_id;
self.enter_scope(ScopeFlags::empty(), &it.scope_id);
// Move all bindings from catch clause param scope to catch clause body scope
// to make it easier to resolve references and check redeclare errors
if self.scope.get_flags(parent_scope_id).is_catch_clause() {
let parent_bindings = self.scope.get_bindings_mut(parent_scope_id);
if !parent_bindings.is_empty() {
let parent_bindings = parent_bindings.drain(..).collect::<Bindings>();
parent_bindings.values().for_each(|&symbol_id| {
self.symbols.set_scope_id(symbol_id, self.current_scope_id);
});
*self.scope.get_bindings_mut(self.current_scope_id) = parent_bindings;
}
}
self.visit_statements(&it.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_id = self.retrieve_recorded_ast_node();
/* cfg */
control_flow!(self, |cfg| {
cfg.append_condition_to(start_of_condition_graph_ix, test_node_id);
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_id = 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_id);
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);
self.enter_scope(ScopeFlags::empty(), &stmt.scope_id);
if let Some(init) = &stmt.init {
self.visit_for_statement_init(init);
}
/* cfg */