1use fallow_types::extract::{
11 ArgFact, CallResultReads, CallSite, CallTarget, ContractIncomplete, FunctionCalls,
12 FunctionContract, FunctionContractFacts, ImportInfo, LiteralValue, LocalFunctionEscape,
13 OptionKeyFact, ParamFact, ParamKind,
14};
15use oxc_ast::AstKind;
16use oxc_ast::ast::{
17 Argument, ArrowFunctionExpression, BindingPattern, ClassElement, Declaration,
18 ExportDefaultDeclarationKind, Expression, FormalParameter, FormalParameters, Function,
19 IdentifierReference, ObjectPattern, Program, PropertyKey, Statement, VariableDeclaration,
20 VariableDeclarationKind,
21};
22use oxc_ast_visit::{Visit, walk};
23use oxc_semantic::{AstNodes, NodeId, Scoping, Semantic, SymbolId};
24use oxc_span::{GetSpan, Span};
25use oxc_syntax::scope::ScopeFlags;
26use rustc_hash::{FxHashMap, FxHashSet};
27
28use crate::function_body::BodyRef;
29use crate::js_text::JsText as _;
30use crate::opaque_loads::{LoaderCandidates, ReadContext};
31
32pub const MAX_ARG_FACTS: usize = 16;
35
36pub const MAX_LITERAL_STRING_BYTES: usize = 64;
40
41type SiteCall = (CallTarget, Box<str>, CallSite);
43
44type FlatCall = (CallTarget, Box<str>, CallSite, CallResultReads);
47
48pub struct OpaqueLoadInput<'l> {
50 pub loads: &'l FxHashSet<Span>,
52 pub template_reads_root: bool,
55}
56
57pub fn collect(
59 semantic: &Semantic<'_>,
60 program: &Program<'_>,
61 imports: &[ImportInfo],
62 opaque: &OpaqueLoadInput<'_>,
63) -> FunctionContractFacts {
64 let ModuleContracts {
65 declarations,
66 bindings,
67 scopes,
68 ..
69 } = collect_contracts(semantic, program);
70 let loader_candidates: LoaderCandidates = scopes
71 .iter()
72 .zip(&declarations)
73 .enumerate()
74 .filter(|(_, (_, contract))| contract.incomplete != Some(ContractIncomplete::Generator))
76 .filter_map(|(index, (scope, contract))| {
77 Some((scope.span, (u32::try_from(index).ok()?, contract.is_async)))
78 })
79 .collect();
80 let context = ReadContext {
81 template_reads_root: opaque.template_reads_root,
82 loader_candidates: &loader_candidates,
83 };
84 let opaque_loads = crate::opaque_loads::collect(semantic, opaque.loads, context);
85 let (values, literal_consts) = values::value_scope(semantic, program, imports);
86 let mut calls = Vec::new();
87 let mut escapes = Vec::new();
88 collect_local_uses(
89 (semantic, context),
90 &values,
91 &bindings,
92 &scopes,
93 &mut calls,
94 &mut escapes,
95 );
96 collect_import_calls((semantic, context), &values, imports, &mut calls);
97 escapes.sort_by_key(|escape| escape.span_start);
98 FunctionContractFacts {
99 declarations,
100 calls: group_calls(calls),
101 escapes,
102 template_callers: false,
103 direct_eval: calls_direct_eval(semantic),
104 opaque_loads,
105 literal_consts,
106 }
107}
108
109fn with_result_reads(
112 (semantic, context): (&Semantic<'_>, ReadContext<'_>),
113 call_id: NodeId,
114 (target, member_path, site): SiteCall,
115) -> FlatCall {
116 let results = if site.result_used {
117 crate::opaque_loads::read_call_result(semantic, call_id, context)
118 } else {
119 CallResultReads::default()
120 };
121 (target, member_path, site, results)
122}
123
124fn calls_direct_eval(semantic: &Semantic<'_>) -> bool {
126 let scoping = semantic.scoping();
127 let nodes = semantic.nodes();
128 let Some(references) = scoping.root_unresolved_references().get("eval") else {
129 return false;
130 };
131 references.iter().any(|&reference| {
132 let node_id = scoping.get_reference(reference).node_id();
133 let AstKind::IdentifierReference(identifier) = nodes.kind(node_id) else {
134 return false;
135 };
136 let (outer, outer_span) = unwrap_upward(nodes, node_id, identifier.span);
137 matches!(
138 nodes.parent_kind(outer),
139 AstKind::CallExpression(call) if call.callee.span() == outer_span
140 )
141 })
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct ParameterCondition {
149 pub function: Box<str>,
151 pub parameter_index: u32,
153 pub span: (u32, u32),
155 pub negations: u32,
157}
158
159#[must_use]
163pub fn parameter_conditions(path: &std::path::Path, source: &str) -> Vec<ParameterCondition> {
164 let source_type = oxc_span::SourceType::from_path(path).unwrap_or_default();
165 crate::parse_bounded(source, || {
166 let allocator = oxc_allocator::Allocator::default();
167 let parsed = oxc_parser::Parser::new(&allocator, source, source_type).parse();
168 if parsed.fatal_error || parsed.diagnostics.has_errors() {
169 return Vec::new();
170 }
171 let semantic = oxc_semantic::SemanticBuilder::new()
172 .with_build_nodes(true)
173 .build(&parsed.program)
174 .semantic;
175 collect_contracts(&semantic, &parsed.program).conditions
176 })
177 .unwrap_or_default()
178}
179
180struct ModuleContracts {
182 declarations: Vec<FunctionContract>,
183 bindings: Vec<(SymbolId, u32)>,
185 scopes: Vec<SelfCallScope>,
187 conditions: Vec<ParameterCondition>,
189}
190
191fn collect_contracts(semantic: &Semantic<'_>, program: &Program<'_>) -> ModuleContracts {
192 let mut contracts = Vec::new();
193 let mut scopes = Vec::new();
194 let mut conditions = Vec::new();
195 let mut seen: FxHashSet<SymbolId> = FxHashSet::default();
196 let mut bindings = Vec::new();
197 for candidate in module_functions(program) {
198 let Some(symbol) = candidate.symbol else {
199 continue;
200 };
201 if !seen.insert(symbol) {
202 continue;
203 }
204 let Ok(index) = u32::try_from(contracts.len()) else {
205 break;
206 };
207 bindings.push((symbol, index));
208 if let FunctionShape::Function(function) = candidate.shape
211 && let Some(inner) = function.id.as_ref().and_then(|id| id.symbol_id.get())
212 && inner != symbol
213 {
214 bindings.push((inner, index));
215 }
216 let (contract, scope, tests) = build_contract(semantic, &candidate, symbol);
217 conditions.extend(tests.into_iter().map(|test| ParameterCondition {
218 function: contract.binding_name.clone(),
219 parameter_index: test.parameter_index,
220 span: (test.span.start, test.span.end),
221 negations: test.negations,
222 }));
223 contracts.push(contract);
224 scopes.push(scope);
225 }
226 ModuleContracts {
227 declarations: contracts,
228 bindings,
229 scopes,
230 conditions,
231 }
232}
233
234struct SelfCallScope {
236 span: Span,
238 params: Vec<Option<SymbolId>>,
242 keys: Vec<Vec<(Box<str>, SymbolId)>>,
245}
246
247impl SelfCallScope {
248 fn contains(&self, span: Span) -> bool {
250 self.span.start <= span.start && span.end <= self.span.end
251 }
252}
253
254fn collect_local_uses(
256 (semantic, context): (&Semantic<'_>, ReadContext<'_>),
257 values: &values::ValueScope,
258 bindings: &[(SymbolId, u32)],
259 scopes: &[SelfCallScope],
260 calls: &mut Vec<FlatCall>,
261 escapes: &mut Vec<LocalFunctionEscape>,
262) {
263 let scoping = semantic.scoping();
264 let nodes = semantic.nodes();
265 for &(symbol, index) in bindings {
266 for reference in scoping.get_resolved_references(symbol) {
267 if !reference.is_read() {
268 continue;
269 }
270 let node_id = reference.node_id();
271 let AstKind::IdentifierReference(identifier) = nodes.kind(node_id) else {
272 continue;
273 };
274 match local_use(nodes, node_id, identifier.span) {
275 LocalUse::Call(call_id) => calls.extend(
276 function_call(
277 nodes,
278 (scoping, values),
279 call_id,
280 (CallTarget::Local(index), String::new()),
281 scopes.get(index as usize),
282 )
283 .map(|call| with_result_reads((semantic, context), call_id, call)),
284 ),
285 LocalUse::Export => {}
286 LocalUse::Escape => escapes.push(LocalFunctionEscape {
287 contract: index,
288 span_start: identifier.span.start,
289 }),
290 }
291 }
292 }
293}
294
295struct Candidate<'b, 'a> {
297 name: &'b str,
298 span_start: u32,
299 symbol: Option<SymbolId>,
300 shape: FunctionShape<'b, 'a>,
301 mutable: bool,
302}
303
304#[derive(Clone, Copy)]
305enum FunctionShape<'b, 'a> {
306 Function(&'b Function<'a>),
307 Arrow(&'b ArrowFunctionExpression<'a>),
308}
309
310impl<'b, 'a> FunctionShape<'b, 'a> {
311 fn params(self) -> &'b FormalParameters<'a> {
312 match self {
313 Self::Function(function) => &function.params,
314 Self::Arrow(arrow) => &arrow.params,
315 }
316 }
317
318 fn span(self) -> Span {
319 match self {
320 Self::Function(function) => function.span,
321 Self::Arrow(arrow) => arrow.span,
322 }
323 }
324
325 fn is_async(self) -> bool {
326 match self {
327 Self::Function(function) => function.r#async,
328 Self::Arrow(arrow) => arrow.r#async,
329 }
330 }
331}
332
333fn module_functions<'b, 'a>(program: &'b Program<'a>) -> Vec<Candidate<'b, 'a>> {
334 let mut candidates = Vec::new();
335 for statement in &program.body {
336 match statement {
337 Statement::FunctionDeclaration(function) => push_function(&mut candidates, function),
338 Statement::VariableDeclaration(declaration) => {
339 push_variables(&mut candidates, declaration);
340 }
341 Statement::ExportDeclaration(export) => match &export.declaration {
342 Declaration::FunctionDeclaration(function) => {
343 push_function(&mut candidates, function);
344 }
345 Declaration::VariableDeclaration(declaration) => {
346 push_variables(&mut candidates, declaration);
347 }
348 _ => {}
349 },
350 Statement::ExportDefaultDeclaration(export) => {
351 if let ExportDefaultDeclarationKind::FunctionDeclaration(function) =
352 &export.declaration
353 {
354 push_function(&mut candidates, function);
355 }
356 }
357 _ => {}
358 }
359 }
360 candidates
361}
362
363fn push_function<'b, 'a>(candidates: &mut Vec<Candidate<'b, 'a>>, function: &'b Function<'a>) {
364 if function.body.is_none() {
367 return;
368 }
369 let Some(id) = &function.id else {
370 return;
371 };
372 candidates.push(Candidate {
373 name: id.name.as_str(),
374 span_start: id.span.start,
375 symbol: id.symbol_id.get(),
376 shape: FunctionShape::Function(function),
377 mutable: false,
378 });
379}
380
381fn push_variables<'b, 'a>(
382 candidates: &mut Vec<Candidate<'b, 'a>>,
383 declaration: &'b VariableDeclaration<'a>,
384) {
385 if declaration.declare {
386 return;
387 }
388 let mutable = matches!(
389 declaration.kind,
390 VariableDeclarationKind::Let | VariableDeclarationKind::Var
391 );
392 for declarator in &declaration.declarations {
393 let BindingPattern::BindingIdentifier(id) = &declarator.id else {
394 continue;
395 };
396 let shape = match declarator.init.as_ref().map(unwrap_transparent) {
397 Some(Expression::ArrowFunctionExpression(arrow)) => FunctionShape::Arrow(arrow),
398 Some(Expression::FunctionExpression(function)) => FunctionShape::Function(function),
399 _ => continue,
400 };
401 candidates.push(Candidate {
402 name: id.name.as_str(),
403 span_start: id.span.start,
404 symbol: id.symbol_id.get(),
405 shape,
406 mutable,
407 });
408 }
409}
410
411fn unwrap_transparent<'b, 'a>(mut expr: &'b Expression<'a>) -> &'b Expression<'a> {
413 loop {
414 expr = match expr {
415 Expression::ParenthesizedExpression(inner) => &inner.expression,
416 Expression::TSAsExpression(inner) => &inner.expression,
417 Expression::TSTypeAssertion(inner) => &inner.expression,
418 Expression::TSSatisfiesExpression(inner) => &inner.expression,
419 Expression::TSNonNullExpression(inner) => &inner.expression,
420 _ => return expr,
421 };
422 }
423}
424
425fn build_contract(
426 semantic: &Semantic<'_>,
427 candidate: &Candidate<'_, '_>,
428 symbol: SymbolId,
429) -> (FunctionContract, SelfCallScope, Vec<ConditionTest>) {
430 let scoping = semantic.scoping();
431 let params = candidate.shape.params();
432 let (mut facts, param_symbols) = param_facts(scoping, params);
433 let tracked: Vec<Option<SymbolId>> = param_symbols
436 .iter()
437 .copied()
438 .chain(
439 facts
440 .iter()
441 .flat_map(|fact| &fact.keys)
442 .map(|key| key_symbol(params, key)),
443 )
444 .collect();
445
446 let mut scan = BodyScan {
447 scoping,
448 params: &tracked,
449 condition_reads: vec![0; tracked.len()],
450 condition_tests: Vec::new(),
451 returns_value: false,
452 reads_arguments: false,
453 calls_eval: false,
454 function_depth: 0,
455 non_arrow_depth: 0,
456 };
457 let (body, is_arrow) = match candidate.shape {
458 FunctionShape::Function(function) => (function.body.as_deref().map(BodyRef::Block), false),
459 FunctionShape::Arrow(arrow) => (Some(BodyRef::arrow(&arrow.body)), true),
460 };
461 walk::walk_formal_parameters(&mut scan, params);
464 if let Some(body) = body {
465 if matches!(body, BodyRef::Concise(_)) {
466 scan.returns_value = true;
467 }
468 body.visit(&mut scan);
469 }
470 let (param_reads, key_reads) = scan.condition_reads.split_at(param_symbols.len());
471 for (fact, reads) in facts.iter_mut().zip(param_reads) {
472 fact.condition_reads = *reads;
473 }
474 for (key, reads) in facts
475 .iter_mut()
476 .flat_map(|fact| &mut fact.keys)
477 .zip(key_reads)
478 {
479 key.condition_reads = *reads;
480 }
481
482 let incomplete = incomplete_reason(semantic, candidate, symbol, &scan, is_arrow);
483 let scope = SelfCallScope {
484 span: candidate.shape.span(),
485 params: param_symbols
486 .iter()
487 .zip(&facts)
488 .map(|(symbol, fact)| symbol.filter(|_| !fact.written && !fact.is_rest))
490 .collect(),
491 keys: facts
492 .iter()
493 .map(|fact| {
494 fact.keys
495 .iter()
496 .filter(|key| !key.written)
497 .filter_map(|key| {
498 key_symbol(params, key).map(|symbol| (key.key.clone(), symbol))
499 })
500 .collect()
501 })
502 .collect(),
503 };
504 let contract = FunctionContract {
505 binding_name: candidate.name.into(),
506 span_start: candidate.span_start,
507 params: facts,
508 returns_value: scan.returns_value,
509 is_async: candidate.shape.is_async(),
510 incomplete,
511 };
512 let parameter_count = contract.params.len();
515 let tests = scan
516 .condition_tests
517 .into_iter()
518 .filter(|test| {
519 usize::try_from(test.parameter_index).is_ok_and(|index| index < parameter_count)
520 })
521 .collect();
522 (contract, scope, tests)
523}
524
525fn param_facts(
528 scoping: &Scoping,
529 params: &FormalParameters<'_>,
530) -> (Vec<ParamFact>, Vec<Option<SymbolId>>) {
531 let mut facts = Vec::new();
532 let mut symbols = Vec::new();
533 for param in ¶ms.items {
534 let (name, kind, symbol) = pattern_fact(¶m.pattern);
535 symbols.push(symbol);
536 facts.push(ParamFact {
537 name,
538 span_start: param.span.start,
539 kind,
540 optional: param.optional,
541 has_default: param.initializer.is_some(),
542 is_rest: false,
543 condition_reads: 0,
544 written: pattern_written(scoping, ¶m.pattern),
545 keys: option_keys(scoping, param),
546 });
547 }
548 if let Some(rest) = ¶ms.rest {
549 let (name, kind, symbol) = pattern_fact(&rest.rest.argument);
550 symbols.push(symbol);
551 facts.push(ParamFact {
552 name,
553 span_start: rest.span.start,
554 kind,
555 optional: false,
556 has_default: false,
557 is_rest: true,
558 condition_reads: 0,
559 written: pattern_written(scoping, &rest.rest.argument),
560 keys: Vec::new(),
561 });
562 }
563 (facts, symbols)
564}
565
566fn pattern_written(scoping: &Scoping, pattern: &BindingPattern<'_>) -> bool {
572 pattern.get_binding_identifiers().iter().any(|id| {
573 id.symbol_id.get().is_some_and(|symbol| {
574 !scoping.symbol_redeclarations(symbol).is_empty()
575 || scoping
576 .get_resolved_references(symbol)
577 .any(oxc_semantic::Reference::is_write)
578 })
579 })
580}
581
582fn option_keys(scoping: &Scoping, param: &FormalParameter<'_>) -> Vec<OptionKeyFact> {
584 let Some((pattern, pattern_default)) = object_pattern(¶m.pattern) else {
585 return Vec::new();
586 };
587 if let Some(default) = param.initializer.as_deref().or(pattern_default)
589 && !matches!(
590 unwrap_transparent(default),
591 Expression::ObjectExpression(object) if object.properties.is_empty()
592 )
593 {
594 return Vec::new();
595 }
596 let mut keys: Vec<OptionKeyFact> = Vec::new();
597 for property in &pattern.properties {
598 if property.computed {
599 continue;
600 }
601 let key = match &property.key {
602 PropertyKey::StaticIdentifier(id) => id.name.as_str().to_string(),
603 PropertyKey::StringLiteral(literal) => literal.value.text().to_string(),
604 _ => continue,
605 };
606 if values::PROTOTYPE_KEYS.contains(&key.as_str()) || key.len() > values::MAX_KEY_BYTES {
607 continue;
608 }
609 let (id, has_default) = match &property.value {
610 BindingPattern::BindingIdentifier(id) => (id, false),
611 BindingPattern::AssignmentPattern(assignment) => match &assignment.left {
612 BindingPattern::BindingIdentifier(id) => (id, true),
613 _ => continue,
614 },
615 _ => continue,
616 };
617 if keys.iter().any(|existing| *existing.key == *key) {
618 continue;
619 }
620 keys.push(OptionKeyFact {
621 key: key.into(),
622 binding: id.name.as_str().into(),
623 span_start: id.span.start,
624 has_default,
625 condition_reads: 0,
626 written: id.symbol_id.get().is_none_or(|symbol| {
627 !scoping.symbol_redeclarations(symbol).is_empty()
628 || scoping
629 .get_resolved_references(symbol)
630 .any(oxc_semantic::Reference::is_write)
631 }),
632 });
633 }
634 keys
635}
636
637fn object_pattern<'b, 'a>(
640 pattern: &'b BindingPattern<'a>,
641) -> Option<(&'b ObjectPattern<'a>, Option<&'b Expression<'a>>)> {
642 match pattern {
643 BindingPattern::ObjectPattern(object) => Some((object, None)),
644 BindingPattern::AssignmentPattern(assignment) => match &assignment.left {
645 BindingPattern::ObjectPattern(object) => Some((object, Some(&assignment.right))),
646 _ => None,
647 },
648 _ => None,
649 }
650}
651
652fn key_symbol(params: &FormalParameters<'_>, key: &OptionKeyFact) -> Option<SymbolId> {
654 params.items.iter().find_map(|param| {
655 param
656 .pattern
657 .get_binding_identifiers()
658 .into_iter()
659 .find(|id| id.span.start == key.span_start)
660 .and_then(|id| id.symbol_id.get())
661 })
662}
663
664fn pattern_fact(pattern: &BindingPattern<'_>) -> (Option<Box<str>>, ParamKind, Option<SymbolId>) {
665 match pattern {
666 BindingPattern::BindingIdentifier(id) => (
667 Some(id.name.as_str().into()),
668 ParamKind::Identifier,
669 id.symbol_id.get(),
670 ),
671 BindingPattern::ObjectPattern(_) => (None, ParamKind::Object, None),
672 BindingPattern::ArrayPattern(_) => (None, ParamKind::Array, None),
673 BindingPattern::AssignmentPattern(assignment) => pattern_fact(&assignment.left),
674 }
675}
676
677fn incomplete_reason(
678 semantic: &Semantic<'_>,
679 candidate: &Candidate<'_, '_>,
680 symbol: SymbolId,
681 scan: &BodyScan<'_, '_>,
682 is_arrow: bool,
683) -> Option<ContractIncomplete> {
684 let scoping = semantic.scoping();
685 let nodes = semantic.nodes();
686 let mut bodies = 0usize;
687 let mut signatures = 0usize;
688 let mut others = 0usize;
689 for declaration in scoping.symbol_declarations(symbol) {
690 match nodes.kind(declaration) {
691 AstKind::Function(function) if function.body.is_some() => bodies += 1,
692 AstKind::Function(_) => signatures += 1,
693 _ => others += 1,
694 }
695 }
696 let params = candidate.shape.params();
697 let has_decorator = params
698 .items
699 .iter()
700 .any(|param| !param.decorators.is_empty())
701 || params
702 .rest
703 .as_ref()
704 .is_some_and(|rest| !rest.decorators.is_empty());
705 let generator =
706 matches!(candidate.shape, FunctionShape::Function(function) if function.generator);
707 if signatures > 0 && bodies == 1 && others == 0 {
708 Some(ContractIncomplete::Overload)
709 } else if bodies + others > 1 {
710 Some(ContractIncomplete::DuplicateDeclaration)
711 } else if candidate.mutable {
712 Some(ContractIncomplete::MutableBinding)
713 } else if scoping
714 .get_resolved_references(symbol)
715 .any(oxc_semantic::Reference::is_write)
716 {
717 Some(ContractIncomplete::Reassigned)
718 } else if generator {
719 Some(ContractIncomplete::Generator)
720 } else if has_decorator {
721 Some(ContractIncomplete::Decorator)
722 } else if scan.reads_arguments && !is_arrow {
723 Some(ContractIncomplete::ArgumentsRead)
724 } else if scan.calls_eval {
725 Some(ContractIncomplete::DirectEval)
726 } else {
727 None
728 }
729}
730
731struct ConditionTest {
733 parameter_index: u32,
736 span: Span,
737 negations: u32,
738}
739
740struct BodyScan<'s, 'p> {
742 scoping: &'s Scoping,
743 params: &'p [Option<SymbolId>],
744 condition_reads: Vec<u32>,
745 condition_tests: Vec<ConditionTest>,
747 returns_value: bool,
748 reads_arguments: bool,
749 calls_eval: bool,
752 function_depth: u32,
754 non_arrow_depth: u32,
756}
757
758impl<'a> BodyScan<'_, '_> {
759 fn visit_class_element_outer(&mut self, element: &ClassElement<'a>) {
761 let (decorators, key, computed) = match element {
762 ClassElement::MethodDefinition(method) => {
763 (&method.decorators, &method.key, method.computed)
764 }
765 ClassElement::PropertyDefinition(property) => {
766 (&property.decorators, &property.key, property.computed)
767 }
768 ClassElement::AccessorProperty(accessor) => {
769 (&accessor.decorators, &accessor.key, accessor.computed)
770 }
771 ClassElement::StaticBlock(_) | ClassElement::TSIndexSignature(_) => return,
772 };
773 self.visit_decorators(decorators);
774 if computed {
775 self.visit_property_key(key);
776 }
777 if let ClassElement::MethodDefinition(method) = element {
779 for param in &method.value.params.items {
780 self.visit_decorators(¶m.decorators);
781 }
782 }
783 }
784
785 fn visit_class_element_inner(&mut self, element: &ClassElement<'a>) {
787 match element {
788 ClassElement::MethodDefinition(method) => {
789 self.visit_function(&method.value, ScopeFlags::Function);
790 }
791 ClassElement::PropertyDefinition(property) => {
792 if let Some(value) = &property.value {
793 self.visit_expression(value);
794 }
795 }
796 ClassElement::AccessorProperty(accessor) => {
797 if let Some(value) = &accessor.value {
798 self.visit_expression(value);
799 }
800 }
801 ClassElement::StaticBlock(block) => self.visit_static_block(block),
802 ClassElement::TSIndexSignature(_) => {}
803 }
804 }
805}
806
807impl BodyScan<'_, '_> {
808 fn count_test(&mut self, test: &Expression<'_>) {
809 let mut expr = unwrap_transparent(test);
810 let mut negations = 0;
811 while let Expression::UnaryExpression(unary) = expr
812 && unary.operator == oxc_syntax::operator::UnaryOperator::LogicalNot
813 {
814 expr = unwrap_transparent(&unary.argument);
815 negations += 1;
816 }
817 let Expression::Identifier(identifier) = expr else {
818 return;
819 };
820 let Some(symbol) = self.resolve(identifier) else {
821 return;
822 };
823 let Some(index) = self.params.iter().position(|param| *param == Some(symbol)) else {
824 return;
825 };
826 self.condition_reads[index] += 1;
827 if let Ok(parameter_index) = u32::try_from(index) {
828 self.condition_tests.push(ConditionTest {
829 parameter_index,
830 span: test.span(),
831 negations,
832 });
833 }
834 }
835
836 fn resolve(&self, identifier: &IdentifierReference<'_>) -> Option<SymbolId> {
837 let reference = identifier.reference_id.get()?;
838 self.scoping.get_reference(reference).symbol_id()
839 }
840}
841
842impl<'a> Visit<'a> for BodyScan<'_, '_> {
843 fn visit_function(&mut self, function: &Function<'a>, flags: ScopeFlags) {
844 self.function_depth += 1;
845 self.non_arrow_depth += 1;
846 walk::walk_function(self, function, flags);
847 self.non_arrow_depth -= 1;
848 self.function_depth -= 1;
849 }
850
851 fn visit_arrow_function_expression(&mut self, arrow: &ArrowFunctionExpression<'a>) {
852 self.function_depth += 1;
853 walk::walk_arrow_function_expression(self, arrow);
854 self.function_depth -= 1;
855 }
856
857 fn visit_class(&mut self, class: &oxc_ast::ast::Class<'a>) {
858 self.visit_decorators(&class.decorators);
863 if let Some(heritage) = &class.heritage {
864 self.visit_expression(&heritage.expression);
865 }
866 for element in &class.body.body {
867 self.visit_class_element_outer(element);
868 }
869 self.function_depth += 1;
870 self.non_arrow_depth += 1;
871 for element in &class.body.body {
872 self.visit_class_element_inner(element);
873 }
874 self.non_arrow_depth -= 1;
875 self.function_depth -= 1;
876 }
877
878 fn visit_return_statement(&mut self, statement: &oxc_ast::ast::ReturnStatement<'a>) {
879 if self.function_depth == 0 && statement.argument.is_some() {
880 self.returns_value = true;
881 }
882 walk::walk_return_statement(self, statement);
883 }
884
885 fn visit_call_expression(&mut self, call: &oxc_ast::ast::CallExpression<'a>) {
886 if let Expression::Identifier(callee) = &call.callee
887 && callee.name == "eval"
888 && self.resolve(callee).is_none()
889 {
890 self.calls_eval = true;
891 }
892 walk::walk_call_expression(self, call);
893 }
894
895 fn visit_identifier_reference(&mut self, identifier: &IdentifierReference<'a>) {
896 if self.non_arrow_depth == 0
897 && identifier.name == "arguments"
898 && self.resolve(identifier).is_none()
899 {
900 self.reads_arguments = true;
901 }
902 }
903
904 fn visit_if_statement(&mut self, statement: &oxc_ast::ast::IfStatement<'a>) {
905 self.count_test(&statement.test);
906 walk::walk_if_statement(self, statement);
907 }
908
909 fn visit_conditional_expression(&mut self, expr: &oxc_ast::ast::ConditionalExpression<'a>) {
910 self.count_test(&expr.test);
911 walk::walk_conditional_expression(self, expr);
912 }
913
914 fn visit_while_statement(&mut self, statement: &oxc_ast::ast::WhileStatement<'a>) {
915 self.count_test(&statement.test);
916 walk::walk_while_statement(self, statement);
917 }
918
919 fn visit_do_while_statement(&mut self, statement: &oxc_ast::ast::DoWhileStatement<'a>) {
920 self.count_test(&statement.test);
921 walk::walk_do_while_statement(self, statement);
922 }
923
924 fn visit_for_statement(&mut self, statement: &oxc_ast::ast::ForStatement<'a>) {
925 if let Some(test) = &statement.test {
926 self.count_test(test);
927 }
928 walk::walk_for_statement(self, statement);
929 }
930}
931
932enum LocalUse {
933 Call(NodeId),
934 Export,
935 Escape,
936}
937
938fn local_use(nodes: &AstNodes<'_>, node_id: NodeId, span: Span) -> LocalUse {
940 let (outer, outer_span) = unwrap_upward(nodes, node_id, span);
941 let parent = nodes.parent_id(outer);
942 match nodes.kind(parent) {
943 AstKind::CallExpression(call)
944 if call.callee.span() == outer_span
945 && !call.optional
946 && !matches!(nodes.parent_kind(parent), AstKind::ChainExpression(_)) =>
947 {
948 LocalUse::Call(parent)
949 }
950 AstKind::ExportSpecifier(_) | AstKind::JSXClosingElement(_) => LocalUse::Export,
953 AstKind::ExportDefaultDeclaration(_) if outer == node_id => LocalUse::Export,
957 _ => LocalUse::Escape,
958 }
959}
960
961fn unwrap_upward(nodes: &AstNodes<'_>, node_id: NodeId, span: Span) -> (NodeId, Span) {
964 let mut current = node_id;
965 let mut current_span = span;
966 loop {
967 let parent = nodes.parent_id(current);
968 if parent == current {
969 break;
970 }
971 let parent_span = match nodes.kind(parent) {
972 AstKind::ParenthesizedExpression(node) => node.span,
973 AstKind::TSAsExpression(node) if node.expression.span() == current_span => node.span,
974 AstKind::TSSatisfiesExpression(node) if node.expression.span() == current_span => {
975 node.span
976 }
977 AstKind::TSNonNullExpression(node) => node.span,
978 AstKind::TSInstantiationExpression(node) if node.expression.span() == current_span => {
979 node.span
980 }
981 _ => break,
982 };
983 current = parent;
984 current_span = parent_span;
985 }
986 (current, current_span)
987}
988
989fn collect_import_calls(
991 (semantic, context): (&Semantic<'_>, ReadContext<'_>),
992 values: &values::ValueScope,
993 imports: &[ImportInfo],
994 calls: &mut Vec<FlatCall>,
995) {
996 let scoping = semantic.scoping();
997 let nodes = semantic.nodes();
998 for (index, import) in imports.iter().enumerate() {
999 let Ok(import_index) = u32::try_from(index) else {
1000 break;
1001 };
1002 let Some(symbol) = crate::binding_references::admitted_import_symbol(semantic, import)
1003 else {
1004 continue;
1005 };
1006 for reference in scoping.get_resolved_references(symbol) {
1007 if !reference.is_value() {
1008 continue;
1009 }
1010 let node_id = reference.node_id();
1011 let AstKind::IdentifierReference(identifier) = nodes.kind(node_id) else {
1012 continue;
1013 };
1014 let (chain, chain_span, path) = static_member_chain(nodes, node_id, identifier.span);
1015 let LocalUse::Call(call_id) = local_use(nodes, chain, chain_span) else {
1016 continue;
1017 };
1018 if let Some(call) = function_call(
1019 nodes,
1020 (scoping, values),
1021 call_id,
1022 (CallTarget::Import(import_index), path),
1023 None,
1024 ) {
1025 calls.push(with_result_reads((semantic, context), call_id, call));
1026 }
1027 }
1028 }
1029}
1030
1031fn static_member_chain(
1034 nodes: &AstNodes<'_>,
1035 node_id: NodeId,
1036 span: Span,
1037) -> (NodeId, Span, String) {
1038 let mut current = node_id;
1039 let mut current_span = span;
1040 let mut path = String::new();
1041 loop {
1042 let parent = nodes.parent_id(current);
1043 if parent == current {
1044 break;
1045 }
1046 let AstKind::StaticMemberExpression(member) = nodes.kind(parent) else {
1047 break;
1048 };
1049 if member.object.span() != current_span || member.optional {
1050 break;
1051 }
1052 if !path.is_empty() {
1053 path.push('.');
1054 }
1055 path.push_str(member.property.name.as_str());
1056 current = parent;
1057 current_span = member.span;
1058 }
1059 (current, current_span, path)
1060}
1061
1062fn function_call(
1065 nodes: &AstNodes<'_>,
1066 (scoping, values): (&Scoping, &values::ValueScope),
1067 call_id: NodeId,
1068 (target, member_path): (CallTarget, String),
1069 scope: Option<&SelfCallScope>,
1070) -> Option<SiteCall> {
1071 let AstKind::CallExpression(call) = nodes.kind(call_id) else {
1072 return None;
1073 };
1074 let self_call = scope.filter(|scope| scope.contains(call.span));
1075 let arg_count = u32::try_from(call.arguments.len()).unwrap_or(u32::MAX);
1076 let spread_from = call
1077 .arguments
1078 .iter()
1079 .position(Argument::is_spread)
1080 .and_then(|index| u32::try_from(index).ok());
1081 let mut args: Vec<ArgFact> = call
1082 .arguments
1083 .iter()
1084 .take(spread_from.map_or(MAX_ARG_FACTS, |index| MAX_ARG_FACTS.min(index as usize)))
1085 .enumerate()
1086 .map(|(position, argument)| {
1087 let context = ArgContext {
1088 scoping,
1089 values,
1090 pass_through: self_call.map_or(&[][..], |scope| &scope.params),
1091 pass_through_keys: self_call
1092 .and_then(|scope| scope.keys.get(position))
1093 .map_or(&[][..], Vec::as_slice),
1094 };
1095 arg_fact(&context, argument)
1096 })
1097 .collect();
1098 if args.iter().all(|arg| *arg == ArgFact::Unknown) {
1099 args = Vec::new();
1100 }
1101 let site = CallSite {
1102 arg_count,
1103 args,
1104 spread_from,
1105 result_used: result_used(nodes, call_id),
1106 span_start: call.span.start,
1107 };
1108 Some((target, member_path.into_boxed_str(), site))
1109}
1110
1111fn group_calls(mut flat: Vec<FlatCall>) -> Vec<FunctionCalls> {
1114 flat.sort_by_key(|(_, _, site, _)| site.span_start);
1115 let mut groups: Vec<FunctionCalls> = Vec::new();
1116 let mut index: FxHashMap<(CallTarget, Box<str>), usize> = FxHashMap::default();
1117 for (target, member_path, site, results) in flat {
1118 match index.entry((target, member_path)) {
1119 std::collections::hash_map::Entry::Occupied(entry) => {
1120 let group = &mut groups[*entry.get()];
1121 group.sites.push(site);
1122 group.results.merge(results);
1123 }
1124 std::collections::hash_map::Entry::Vacant(entry) => {
1125 let (target, member_path) = entry.key().clone();
1126 entry.insert(groups.len());
1127 groups.push(FunctionCalls {
1128 target,
1129 member_path,
1130 sites: vec![site],
1131 results,
1132 });
1133 }
1134 }
1135 }
1136 for group in &mut groups {
1137 crate::opaque_loads::limit_names(&mut group.results.value);
1138 crate::opaque_loads::limit_names(&mut group.results.promise);
1139 }
1140 groups
1141}
1142
1143struct ArgContext<'s, 'v> {
1145 scoping: &'s Scoping,
1146 values: &'v values::ValueScope,
1147 pass_through: &'s [Option<SymbolId>],
1150 pass_through_keys: &'s [(Box<str>, SymbolId)],
1153}
1154
1155fn arg_fact(context: &ArgContext<'_, '_>, argument: &Argument<'_>) -> ArgFact {
1157 let Some(expr) = argument.as_expression() else {
1158 return ArgFact::Unknown;
1159 };
1160 let scoping = context.scoping;
1161 let expr = unwrap_transparent(expr);
1162 if let Some(literal) = literal_value(scoping, expr) {
1163 return ArgFact::Literal(literal);
1164 }
1165 if let Expression::ObjectExpression(object) = expr {
1166 return values::object_arg(scoping, context.values, object, context.pass_through_keys);
1167 }
1168 if let Some(index) = pass_through_param(scoping, expr, context.pass_through) {
1169 return ArgFact::Param(index);
1170 }
1171 context
1172 .values
1173 .binding(scoping, expr)
1174 .map_or(ArgFact::Unknown, ArgFact::Binding)
1175}
1176
1177fn pass_through_param(
1179 scoping: &Scoping,
1180 expr: &Expression<'_>,
1181 pass_through: &[Option<SymbolId>],
1182) -> Option<u32> {
1183 let Expression::Identifier(identifier) = expr else {
1184 return None;
1185 };
1186 let symbol = scoping
1187 .get_reference(identifier.reference_id.get()?)
1188 .symbol_id()?;
1189 let index = pass_through
1190 .iter()
1191 .position(|param| *param == Some(symbol))?;
1192 u32::try_from(index).ok()
1193}
1194
1195fn literal_value(scoping: &Scoping, expr: &Expression<'_>) -> Option<LiteralValue> {
1196 match expr {
1197 Expression::BooleanLiteral(literal) => Some(LiteralValue::Boolean(literal.value)),
1198 Expression::NullLiteral(_) => Some(LiteralValue::Null),
1199 Expression::NumericLiteral(literal) => Some(number(literal.value)),
1200 Expression::UnaryExpression(unary)
1201 if unary.operator == oxc_syntax::operator::UnaryOperator::UnaryNegation =>
1202 {
1203 match unwrap_transparent(&unary.argument) {
1204 Expression::NumericLiteral(literal) => Some(number(-literal.value)),
1205 _ => None,
1206 }
1207 }
1208 Expression::StringLiteral(literal) => string(&literal.value.text()),
1209 Expression::TemplateLiteral(template) if template.expressions.is_empty() => template
1210 .quasis
1211 .first()
1212 .and_then(|quasi| quasi.value.cooked)
1213 .and_then(|cooked| string(&cooked.text())),
1214 Expression::Identifier(identifier) if identifier.name == "undefined" => {
1215 let resolved = identifier
1216 .reference_id
1217 .get()
1218 .and_then(|reference| scoping.get_reference(reference).symbol_id());
1219 resolved.is_none().then_some(LiteralValue::Undefined)
1220 }
1221 _ => None,
1222 }
1223}
1224
1225fn string(value: &str) -> Option<LiteralValue> {
1226 (value.len() <= MAX_LITERAL_STRING_BYTES).then(|| LiteralValue::String(value.into()))
1227}
1228
1229fn number(value: f64) -> LiteralValue {
1230 LiteralValue::Number(value.to_bits())
1231}
1232
1233fn result_used(nodes: &AstNodes<'_>, call_id: NodeId) -> bool {
1236 let mut current = call_id;
1237 loop {
1238 let parent = nodes.parent_id(current);
1239 if parent == current {
1240 return true;
1241 }
1242 match nodes.kind(parent) {
1243 AstKind::ParenthesizedExpression(_) | AstKind::AwaitExpression(_) => current = parent,
1244 AstKind::UnaryExpression(unary)
1245 if unary.operator == oxc_syntax::operator::UnaryOperator::Void =>
1246 {
1247 current = parent;
1248 }
1249 AstKind::ExpressionStatement(_) => return false,
1250 _ => return true,
1251 }
1252 }
1253}
1254
1255#[path = "function_contracts_values.rs"]
1256mod values;
1257
1258#[cfg(test)]
1259#[path = "function_contracts_tests.rs"]
1260mod tests;