-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
toStatement.ts
62 lines (50 loc) 路 1.67 KB
/
toStatement.ts
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
import {
isStatement,
isFunction,
isClass,
isAssignmentExpression,
} from "../validators/generated";
import { expressionStatement } from "../builders/generated";
import type * as t from "..";
export default toStatement as {
(node: t.AssignmentExpression, ignore?: boolean): t.ExpressionStatement;
<T extends t.Statement>(node: T, ignore: false): T;
<T extends t.Statement>(node: T, ignore?: boolean): T | false;
(node: t.Class, ignore: false): t.ClassDeclaration;
(node: t.Class, ignore?: boolean): t.ClassDeclaration | false;
(node: t.Function, ignore: false): t.FunctionDeclaration;
(node: t.Function, ignore?: boolean): t.FunctionDeclaration | false;
(node: t.Node, ignore: false): t.Statement;
(node: t.Node, ignore?: boolean): t.Statement | false;
};
function toStatement(node: t.Node, ignore?: boolean): t.Statement | false {
if (isStatement(node)) {
return node;
}
let mustHaveId = false;
let newType;
if (isClass(node)) {
mustHaveId = true;
newType = "ClassDeclaration" as const;
} else if (isFunction(node)) {
mustHaveId = true;
newType = "FunctionDeclaration" as const;
} else if (isAssignmentExpression(node)) {
return expressionStatement(node);
}
// @ts-expect-error todo(flow->ts): node.id might be missing
if (mustHaveId && !node.id) {
newType = false as false;
}
if (!newType) {
if (ignore) {
return false;
} else {
throw new Error(`cannot turn ${node.type} to a statement`);
}
}
// @ts-expect-error manipulating node.type
node.type = newType;
// @ts-expect-error todo(flow->ts) refactor to avoid type unsafe mutations like reassigning node type above
return node;
}