| 1 |
import { |
| 2 |
isStatement, |
| 3 |
isFunction, |
| 4 |
isClass, |
| 5 |
isAssignmentExpression, |
| 6 |
} from "../validators/generated"; |
| 7 |
import { expressionStatement } from "../builders/generated"; |
| 8 |
import type * as t from ".."; |
| 9 |
|
| 10 |
export default toStatement as { |
| 11 |
(node: t.AssignmentExpression, ignore?: boolean): t.ExpressionStatement; |
| 12 |
|
| 13 |
<T extends t.Statement>(node: T, ignore: false): T; |
| 14 |
<T extends t.Statement>(node: T, ignore?: boolean): T | false; |
| 15 |
|
| 16 |
(node: t.Class, ignore: false): t.ClassDeclaration; |
| 17 |
(node: t.Class, ignore?: boolean): t.ClassDeclaration | false; |
| 18 |
|
| 19 |
(node: t.Function, ignore: false): t.FunctionDeclaration; |
| 20 |
(node: t.Function, ignore?: boolean): t.FunctionDeclaration | false; |
| 21 |
|
| 22 |
(node: t.Node, ignore: false): t.Statement; |
| 23 |
(node: t.Node, ignore?: boolean): t.Statement | false; |
| 24 |
}; |
| 25 |
|
| 26 |
function toStatement(node: t.Node, ignore?: boolean): t.Statement | false { |
| 27 |
if (isStatement(node)) { |
| 28 |
return node; |
| 29 |
} |
| 30 |
|
| 31 |
let mustHaveId = false; |
| 32 |
let newType; |
| 33 |
|
| 34 |
if (isClass(node)) { |
| 35 |
mustHaveId = true; |
| 36 |
newType = "ClassDeclaration" as const; |
| 37 |
} else if (isFunction(node)) { |
| 38 |
mustHaveId = true; |
| 39 |
newType = "FunctionDeclaration" as const; |
| 40 |
} else if (isAssignmentExpression(node)) { |
| 41 |
return expressionStatement(node); |
| 42 |
} |
| 43 |
|
| 44 |
// @ts-expect-error todo(flow->ts): node.id might be missing |
| 45 |
if (mustHaveId && !node.id) { |
| 46 |
newType = false as false; |
| 47 |
} |
| 48 |
|
| 49 |
if (!newType) { |
| 50 |
if (ignore) { |
| 51 |
return false; |
| 52 |
} else { |
| 53 |
throw new Error(`cannot turn ${node.type} to a statement`); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
// @ts-expect-error manipulating node.type |
| 58 |
node.type = newType; |
| 59 |
|
| 60 |
// @ts-expect-error todo(flow->ts) refactor to avoid type unsafe mutations like reassigning node type above |
| 61 |
return node; |
| 62 |
} |