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