Debian Codegraph @

packages/babel-types/src/converters/toExpression.ts

raw
1 import {
2 isExpression,
3 isFunction,
4 isClass,
5 isExpressionStatement,
6 } from "../validators/generated";
7 import type * as t from "..";
8
9 export default toExpression as {
10 (node: t.Function): t.FunctionExpression;
11 (node: t.Class): t.ClassExpression;
12 (
13 node: t.ExpressionStatement | t.Expression | t.Class | t.Function,
14 ): t.Expression;
15 };
16
17 function toExpression(
18 node: t.ExpressionStatement | t.Expression | t.Class | t.Function,
19 ): t.Expression {
20 if (isExpressionStatement(node)) {
21 node = node.expression;
22 }
23
24 // return unmodified node
25 // important for things like ArrowFunctions where
26 // type change from ArrowFunction to FunctionExpression
27 // produces bugs like -> `()=>a` to `function () a`
28 // without generating a BlockStatement for it
29 // ref: https://github.com/babel/babili/issues/130
30 if (isExpression(node)) {
31 return node;
32 }
33
34 // convert all classes and functions
35 // ClassDeclaration -> ClassExpression
36 // FunctionDeclaration, ObjectMethod, ClassMethod -> FunctionExpression
37 if (isClass(node)) {
38 // @ts-expect-error todo(flow->ts): avoid type unsafe mutations
39 node.type = "ClassExpression";
40 } else if (isFunction(node)) {
41 // @ts-expect-error todo(flow->ts): avoid type unsafe mutations
42 node.type = "FunctionExpression";
43 }
44
45 // if it's still not an expression
46 if (!isExpression(node)) {
47 throw new Error(`cannot turn ${node.type} to an expression`);
48 }
49
50 return node;
51 }