Debian Codegraph @

packages/babel-traverse/src/path/inference/inferer-reference.ts

raw symbols SCIP
1 import type NodePath from "../index";
2 import {
3 BOOLEAN_NUMBER_BINARY_OPERATORS,
4 createTypeAnnotationBasedOnTypeof,
5 numberTypeAnnotation,
6 voidTypeAnnotation,
7 } from "@babel/types";
8 import type * as t from "@babel/types";
9 import type Binding from "../../scope/binding";
10
11 import { createUnionType } from "./util";
12
13 export default function (this: NodePath<t.Identifier>, node: t.Identifier) {
14 if (!this.isReferenced()) return;
15
16 // check if a binding exists of this value and if so then return a union type of all
17 // possible types that the binding could be
18 const binding = this.scope.getBinding(node.name);
19 if (binding) {
20 if (binding.identifier.typeAnnotation) {
21 return binding.identifier.typeAnnotation;
22 } else {
23 return getTypeAnnotationBindingConstantViolations(
24 binding,
25 this,
26 node.name,
27 );
28 }
29 }
30
31 // built-in values
32 if (node.name === "undefined") {
33 return voidTypeAnnotation();
34 } else if (node.name === "NaN" || node.name === "Infinity") {
35 return numberTypeAnnotation();
36 } else if (node.name === "arguments") {
37 // todo
38 }
39 }
40
41 function getTypeAnnotationBindingConstantViolations(
42 binding: Binding,
43 path: NodePath<t.Identifier>,
44 name: string,
45 ) {
46 const types = [];
47
48 const functionConstantViolations: NodePath[] = [];
49 let constantViolations = getConstantViolationsBefore(
50 binding,
51 path,
52 functionConstantViolations,
53 );
54
55 const testType = getConditionalAnnotation(binding, path, name);
56 if (testType) {
57 const testConstantViolations = getConstantViolationsBefore(
58 binding,
59 testType.ifStatement,
60 );
61
62 // remove constant violations observed before the IfStatement
63 constantViolations = constantViolations.filter(
64 path => testConstantViolations.indexOf(path) < 0,
65 );
66
67 // clear current types and add in observed test type
68 types.push(testType.typeAnnotation);
69 }
70
71 if (constantViolations.length) {
72 // pick one constant from each scope which will represent the last possible
73 // control flow path that it could've taken/been
74 /* This code is broken for the following problems:
75 * It thinks that assignments can only happen in scopes.
76 * What about conditionals, if statements without block,
77 * or guarded assignments.
78 * It also checks to see if one of the assignments is in the
79 * same scope and uses that as the only "violation". However,
80 * the binding is returned by `getConstantViolationsBefore` so we for
81 * sure always going to return that as the only "violation".
82 let rawConstantViolations = constantViolations.reverse();
83 let visitedScopes = [];
84 constantViolations = [];
85 for (let violation of (rawConstantViolations: Array<NodePath>)) {
86 let violationScope = violation.scope;
87 if (visitedScopes.indexOf(violationScope) >= 0) continue;
88
89 visitedScopes.push(violationScope);
90 constantViolations.push(violation);
91
92 if (violationScope === path.scope) {
93 constantViolations = [violation];
94 break;
95 }
96 }*/
97
98 // add back on function constant violations since we can't track calls
99 constantViolations.push(...functionConstantViolations);
100
101 // push on inferred types of violated paths
102 for (const violation of constantViolations) {
103 types.push(violation.getTypeAnnotation());
104 }
105 }
106
107 if (!types.length) {
108 return;
109 }
110
111 return createUnionType(types);
112 }
113
114 function getConstantViolationsBefore(
115 binding: Binding,
116 path: NodePath,
117 functions?: NodePath[],
118 ) {
119 const violations = binding.constantViolations.slice();
120 violations.unshift(binding.path);
121 return violations.filter(violation => {
122 violation = violation.resolve();
123 const status = violation._guessExecutionStatusRelativeTo(path);
124 if (functions && status === "unknown") functions.push(violation);
125 return status === "before";
126 });
127 }
128
129 function inferAnnotationFromBinaryExpression(
130 name: string,
131 path: NodePath<t.BinaryExpression>,
132 ) {
133 const operator = path.node.operator;
134
135 const right = path.get("right").resolve();
136 const left = path.get("left").resolve();
137
138 let target;
139 if (left.isIdentifier({ name })) {
140 target = right;
141 } else if (right.isIdentifier({ name })) {
142 target = left;
143 }
144
145 if (target) {
146 if (operator === "===") {
147 return target.getTypeAnnotation();
148 }
149 if (BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
150 return numberTypeAnnotation();
151 }
152
153 return;
154 }
155
156 if (operator !== "===" && operator !== "==") return;
157
158 //
159 let typeofPath: NodePath<t.UnaryExpression>;
160 let typePath: NodePath<t.Expression>;
161 if (left.isUnaryExpression({ operator: "typeof" })) {
162 typeofPath = left;
163 typePath = right as NodePath<t.Expression>;
164 } else if (right.isUnaryExpression({ operator: "typeof" })) {
165 typeofPath = right;
166 typePath = left as NodePath<t.Expression>;
167 }
168
169 if (!typeofPath) return;
170 // and that the argument of the typeof path references us!
171 if (!typeofPath.get("argument").isIdentifier({ name })) return;
172
173 // ensure that the type path is a Literal
174 typePath = typePath.resolve() as NodePath<t.Expression>;
175 if (!typePath.isLiteral()) return;
176
177 // and that it's a string so we can infer it
178 // @ts-expect-error todo(flow->ts): value is not defined for NullLiteral and some other
179 const typeValue = typePath.node.value;
180 if (typeof typeValue !== "string") return;
181
182 // turn type value into a type annotation
183 // @ts-expect-error todo(flow->ts): move validation from helper or relax type constraint to just a string
184 return createTypeAnnotationBasedOnTypeof(typeValue);
185 }
186
187 function getParentConditionalPath(
188 binding: Binding,
189 path: NodePath,
190 name: string,
191 ) {
192 let parentPath;
193 while ((parentPath = path.parentPath)) {
194 if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) {
195 if (path.key === "test") {
196 return;
197 }
198
199 return parentPath as NodePath<t.IfStatement | t.ConditionalExpression>;
200 }
201 if (parentPath.isFunction()) {
202 if (parentPath.parentPath.scope.getBinding(name) !== binding) return;
203 }
204
205 path = parentPath;
206 }
207 }
208
209 function getConditionalAnnotation<T extends t.Node>(
210 binding: Binding,
211 path: NodePath<T>,
212 name?: string,
213 ): {
214 typeAnnotation: t.FlowType | t.TSType;
215 ifStatement: NodePath<t.IfStatement | t.ConditionalExpression>;
216 } {
217 const ifStatement = getParentConditionalPath(binding, path, name);
218 if (!ifStatement) return;
219
220 const test = ifStatement.get("test");
221 const paths = [test];
222 const types = [];
223
224 for (let i = 0; i < paths.length; i++) {
225 const path = paths[i];
226
227 if (path.isLogicalExpression()) {
228 if (path.node.operator === "&&") {
229 paths.push(path.get("left"));
230 paths.push(path.get("right"));
231 }
232 } else if (path.isBinaryExpression()) {
233 const type = inferAnnotationFromBinaryExpression(name, path);
234 if (type) types.push(type);
235 }
236 }
237
238 if (types.length) {
239 return {
240 typeAnnotation: createUnionType(types),
241 ifStatement,
242 };
243 }
244
245 return getConditionalAnnotation(binding, ifStatement, name);
246 }