• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import * as ts from "typescript";
17import { Compiler } from "../compiler";
18import { VReg } from "../irnodes";
19import { containSpreadElement } from "../base/util";
20import { createArrayFromElements } from "./arrayLiteralExpression";
21
22export function compileNewExpression(expr: ts.NewExpression, compiler: Compiler) {
23    let pandaGen = compiler.getPandaGen();
24    let ctorReg = pandaGen.getTemp();
25
26    // get the ctor function
27    compiler.compileExpression(expr.expression);
28    pandaGen.storeAccumulator(expr, ctorReg);
29
30    if (containSpreadElement(expr.arguments)) {
31        let argRegs = pandaGen.getTemp();
32        createArrayFromElements(expr, compiler, <ts.NodeArray<ts.Expression>>expr.arguments, argRegs);
33
34        pandaGen.newObjSpread(expr, ctorReg);
35        pandaGen.freeTemps(ctorReg, argRegs);
36
37        return;
38    }
39
40    // prepare arguments for newobj.dyn.range instruction
41    let numArgs = 1; // for the ctor
42    if (expr.arguments) {
43        numArgs += expr.arguments.length;
44    }
45
46    let argRegs = new Array<VReg>(numArgs);
47    argRegs[0] = ctorReg;
48
49    let argIndex = 1;
50    if (expr.arguments) {
51        // store ctor arguments in registers
52        expr.arguments.forEach((argExpr: ts.Expression) => {
53            let argReg = pandaGen.getTemp();
54            compiler.compileExpression(argExpr);
55            pandaGen.storeAccumulator(expr, argReg);
56            argRegs[argIndex++] = argReg;
57        });
58    }
59
60    // generate the instruction to create new instance
61    pandaGen.newObject(expr, argRegs);
62
63    // free temp registers
64    pandaGen.freeTemps(...argRegs);
65}