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 { GeneratorFunctionBuilder } from "../function/generatorFunctionBuilder"; 18import { DiagnosticCode, DiagnosticError } from "../diagnostic"; 19import { CacheList, getVregisterCache } from "../base/vregisterCache"; 20import { Compiler } from "../compiler"; 21 22export function compileYieldExpression(compiler: Compiler, expr: ts.YieldExpression) { 23 if (!(compiler.getFuncBuilder() instanceof GeneratorFunctionBuilder)) { 24 throw new DiagnosticError(expr.parent, DiagnosticCode.A_yield_expression_is_only_allowed_in_a_generator_body); 25 } 26 27 expr.asteriskToken ? genYieldStarExpr(compiler, expr) : genYieldExpr(compiler, expr); 28} 29 30function genYieldExpr(compiler: Compiler, expr: ts.YieldExpression) { 31 let pandaGen = compiler.getPandaGen(); 32 let funcBuilder = <GeneratorFunctionBuilder>compiler.getFuncBuilder(); 33 if (expr.expression) { 34 let retValue = pandaGen.getTemp(); 35 36 compiler.compileExpression(expr.expression); 37 pandaGen.storeAccumulator(expr, retValue); 38 39 funcBuilder.yield(expr, retValue); 40 41 pandaGen.freeTemps(retValue); 42 } else { 43 funcBuilder.yield(expr, getVregisterCache(pandaGen, CacheList.undefined)); 44 } 45} 46 47function genYieldStarExpr(compiler: Compiler, expr: ts.YieldExpression) { 48 let funcBuilder = <GeneratorFunctionBuilder>compiler.getFuncBuilder(); 49 if (!expr.expression) { 50 throw new Error("yield* must have an expression!"); 51 } 52 compiler.compileExpression(expr.expression!); 53 funcBuilder.yieldStar(expr); 54}