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 { 17 expect 18} from 'chai'; 19import 'mocha'; 20import { 21 Returnundefined, 22 Lda, 23 VReg 24} from "../../src/irnodes"; 25import { PandaGen } from "../../src/pandagen"; 26import { LocalVariable } from "../../src/variable"; 27import { checkInstructions, compileMainSnippet, SnippetCompiler } from "../utils/base"; 28import { creatAstFromSnippet } from "../utils/asthelper" 29 30describe("ThisKeyword", function () { 31 let pandaGen: PandaGen; 32 33 beforeEach(function () { 34 pandaGen = new PandaGen("" /* internalName */, creatAstFromSnippet(""), 0 /* number of parameters */); 35 }); 36 37 it("this in global scope", function () { 38 let snippetCompiler = new SnippetCompiler(); 39 snippetCompiler.compile("this"); 40 let globalScope = snippetCompiler.getGlobalScope(); 41 let insns = snippetCompiler.getGlobalInsns(); 42 let expected = [ 43 new Lda(new VReg()), 44 new Returnundefined() 45 ]; 46 expect(checkInstructions(insns, expected)).to.be.true; 47 let thisVar = globalScope!.findLocal("this"); 48 expect(thisVar instanceof LocalVariable).to.be.true; 49 }); 50 51 it("this in function scope", function () { 52 let snippetCompiler = new SnippetCompiler(); 53 snippetCompiler.compile("function a() {this}"); 54 let functionPg = snippetCompiler.getPandaGenByName("UnitTest.a"); 55 let functionScope = functionPg!.getScope(); 56 let insns = compileMainSnippet("this;", pandaGen, functionScope); 57 let expected = [ 58 new Lda(new VReg()), 59 new Returnundefined() 60 ]; 61 expect(checkInstructions(insns, expected)).to.be.true; 62 let thisVar = functionScope!.findLocal("this"); 63 expect(thisVar != undefined).to.be.true; 64 expect(thisVar instanceof LocalVariable).to.be.true; 65 }); 66});